我在下面有一个简单的 Java 程序。我已经声明了实例整数变量“x1”和“x2”,从我的类构造函数中的参数初始化它们。 我还声明了一个整数变量“diff”,它计算出“x1”和“x2”之间的差异,但该变量返回零!我不知道问题出在哪里,我的构造函数参数不为零!!!。我将不胜感激
public class Smallest {
int x1;
int x2;
public Smallest(int a,int b){
this.x1=a;
this.x2=b;
}
int diff = x2 - x1;
public void draw(){
System.out.println("X1= "+ x1 +"\n X2= "+ x2 +"\n diff= " +diff);
}
public static void main(String[] args) {
Smallest small=new Smallest(10,20);
small.draw();
}
}
这是输出
X1= 10;
X2= 20;
diff= 0;
最佳答案
这是因为 diff 不在它在编译时设置的任何方法中。您应该将其移至构造函数或任何其他方法以获得正确的值。
例子:
int diff;
public Smallest(int a,int b){
this.x1=a;
this.x2=b;
this.diff=x2 - x1;
}
关于java - 为什么我在初始化实例变量时得到零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26218301/