我需要创建一个字段来计算类的实例数
public class Circle
{
private int diameter;
private int xPosition;
private int yPosition;
private String color;
private boolean isVisible;
private static int count = 0;
/**
* Create a new circle at default position with default color.
*/
public Circle()
{
diameter = 30;
xPosition = 20;
yPosition = 60;
color = "blue";
isVisible = false;
count = count++;
}
public void returnCount(){
System.out.println(count);
}
这就是我一直在玩的东西。我希望每次创建变量时计数都会增加1。但它只是保持在0。
感谢任何帮助,Ciaran。
答案 0 :(得分:2)
仅使用:
count++;
为什么呢?因为:
count = count ++;
类似于这样做:
temp = count ; // temp is 0.
count = count +1; // increment count
count = temp; // assign temp (which is 0) to count.
查看类似的post-increament问题。
答案 1 :(得分:2)
后增量运算符隐式使用临时变量。
所以,
count = count ++;
不等于
count++;
在java。
答案 2 :(得分:1)
这是因为++
运算符的使用无效。
只需更正以下行,即可更正您的代码。
// count = count++; incorrect
count++; // correct
// count = count + 1; // correct
使用count++
时,count
变量加1;但是从运算符返回的值是count
变量的先前值。
您可以通过尝试以下内容来了解这一点。
public class Test {
public static void main(String[] args) {
int count = 0;
System.out.println(count++); // line 1
System.out.println(count++);
}
}
当您在上方运行时,结果就是。
0
1
即“行1”仅打印0
,因为count++
的返回值始终是之前的值。