[英]why am i getting zero while i have initialized my instance variables?
i have a simple java program below. 我下面有一个简单的Java程序。 i have declared instance integer variable "x1" and "x2", initialize them from parameters in my class constructor.
我已经声明了实例整数变量“ x1”和“ x2”,并从我的类构造函数中的参数对其进行了初始化。 i have also declared an integer variable "diff" that works out the difference between "x1" and "x2" but the variable returns zero!!
我还声明了一个整数变量“ diff”,该变量计算出“ x1”和“ x2”之间的差异,但该变量返回零! i don't know where the problem is and my constructor parameters are not zero!!!.
我不知道问题出在哪里,我的构造函数参数也不为零! i will appreciate any help
我将不胜感激
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();
}
}
here's the output 这是输出
X1= 10;
X2= 20;
diff= 0;
This is because diff is not inside any method it set during compile time. 这是因为diff不在编译期间设置的任何方法之内。 You should move it to the constructor or any other method to get correct value.
您应该将其移至构造函数或任何其他方法以获得正确的值。
Example : 范例:
int diff;
public Smallest(int a,int b){
this.x1=a;
this.x2=b;
this.diff=x2 - x1;
}
int diff = x2 - x1;
should be inside the constructor
or inside the method draw()
(depending on what you want to do with it). 应该位于
constructor
内部或方法draw()
内部(取决于您要使用的方法)。
Remember: By default int variables are initialized to 0. Before you call the constructor: 记住:默认情况下,int变量被初始化为0。 在调用构造函数之前 :
x1=0;
x2=0;
diff=x1-x2
=0-0
=0
When you call the constructor you give different values to x1
and x2
but you don't calculate the diff
on the newly updated values. 当您调用构造函数时,您给
x1
和x2
赋予了不同的值,但是您没有计算新更新值的diff
。
After you call the constructor: 调用构造函数后:
x1=10;
x2=20;
diff=0; // you don't recalculate it, it's not in the constructor or in the draw method.
Member variables are initialized before your constructor is called. 在调用构造函数之前,先初始化成员变量。 Thus diff is equal to 0 - 0 since x1 and x2 have not been set yet.
因此,由于尚未设置x1和x2,因此diff等于0-0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.