-1

我是 Java 新手,目前正在尝试学习按值传递的工作原理。我有一个名为 Test 的主类和一个名为 TestMax 的第二个类。我在下面的代码中试图实现的是在主类中为类 TestMax 中的 2 个参数 i 和 j 设置值,并max()通过传递我之前刚刚传递的参数的值来调用该方法。

控制台的输出应该是这样的:

The maximum between 2 and 10 is 10.

我知道我将值传递给方法的方式有问题,(int res = max(i,j)但我花了最后 2 小时来弄清楚为什么这不起作用,但我无法弄清楚。

package testproject;
public class Test {
    /** Main method */
    public static void main(String[] args) {
        TestMax pass = new TestMax();
        pass.setI(2);
        pass.setJ(10);
        int res = max(i,j);
        System.out.println("The maximum between " + pass.getI() +
                " and " + pass.getJ() + " is " + res);
    }
}

二等TestMax:

package testproject;

public class TestMax {

    int i ;
    int j ;

public static int max(int num1, int num2) {

    int result;
    if (num1 > num2)
       result = num1;
    else
       result = num2;

    return result;

}

//Getters & Setters
public void setJ(int j) {
    this.j = j;
}

public int getJ() {
    return j;
}

public void setI(int i) {
    this.i = i;
}

public int getI() {
    return i;
}
4

4 回答 4

4

This has nothing to do with pass-by-value vs pass-by-reference. The problem is this line of code:

int res = max(i,j);

The values i and j are out of scope, and max() is not in your current class, so you need to use getters to access the values and reference the method through the class, like so:

int res = TestMax.max(pass.getI(), pass.getJ());
于 2012-09-23T17:36:10.567 回答
2

这一行:

int res = max(i,j);

没有意义:在该范围内既max没有i也没有j声明。你的编译器应该拒绝这个。

你一定是想写:

int res = TestMax.max(pass.getI(), pass.getJ());
于 2012-09-23T17:35:40.703 回答
1

int res = max(i,j);

在上面的行中,该范围内既没有声明也没有声明max()参数。所以它是一个编译错误。i and j

你应该把它写成:

int res = TestMax.max(pass.getI(), pass.getJ());

于 2012-09-23T18:20:37.243 回答
0

您还可以更改 max 方法,使其不再是静态的,而是使用变量 i 和 j 作为其输入,如下面的代码:

 ...

    public int max() {
        int result;
        if (i > j)
           result = i;
        else
           result = j;

        return result;
    }

...

现在您需要在 main 方法中省略以下行中的参数:

int res = max(i,j);

更改为:

int res = max();

但是,如果您以这种方式更改 TestMax 类,则需要创建一个扩展 Exception 的类,以便在为 i 和 j 赋值之前有人调用 max() 方法时可以抛出它。避免这种情况的另一种方法是构建一个构造函数并在那里获取 i 和 j。

于 2012-09-23T18:04:14.137 回答