【问题标题】:A field to count the amount instances of a class [duplicate]用于计算类实例数量的字段[重复]
【发布时间】:2013-12-08 13:28:45
【问题描述】:
我需要创建一个字段来统计一个类的实例数
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。
【问题讨论】:
标签:
java
class
count
instance
【解决方案1】:
只使用:
count++;
为什么?因为:
count = count ++;
类似于做这样的事情:
temp = count ; // temp is 0.
count = count +1; // increment count
count = temp; // assign temp (which is 0) to count.
查看类似的post-increament 问题。
【解决方案2】:
后自增运算符隐式使用临时变量。
所以,
count = count ++;
不等于
count++;
在java中。
【解决方案3】:
这是因为++ 运算符的使用无效。
您的代码可以通过更正以下行来更正。
// 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++ 的返回值始终是前一个值。