首页 > 解决方案 > 我的程序是如何得到 1 的输出的

问题描述

好吧,所以我正在为高中做 AP comp sci,我对这个程序如何达到 A = 1 感到非常困惑,我没有看到任何关于 x 和 y 的声明。谢谢

public class ClassA
{
    public static void main(String args[])
    {
        ClassA n = new ClassA(1 , 2);  
        int a = 0;
        a = n.methodA(a);
        System.out.println("a =" + a);


    }
    private int myNum1;
    private int myNum2;
    public ClassA(int x, int y)   
    {
        myNum1 = x;
        myNum2 = y;
    }

    public int methodA(int y)
    {
        return myNum1+y;

    }

    public int getMyNum1()
    {
        return myNum1;

    }

    public int getMyNum2()
    {
        return myNum2;
    }
}

标签: javaparameters

解决方案


It doesn't actually matter what you use as parameters for your constructor. You create a and set it to 0, then set a to n.methodA(a) where the parameter a is 0, which returns 1.

You could use any values for your constructor call and it n.methodA(a) would always return 1.

Search for "java visualizer" online for a nice tool that can help you understand what your program does step by step.


推荐阅读