问题描述
我需要创建一个字段来计算类的实例数。
I need to create a field to count the number of instances made by a class
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每次创建一个变量。
This is what Ive been playing with. I was hoping the count would increment by 1 each time a variable is created. However it just stays at 0.
推荐答案
感谢任何帮助,Ciaran。 >
这是因为 ++
运算符的无效使用。
This is because of the invalid use of ++
operator.
// count = count++; incorrect
count++; // correct
// count = count + 1; // correct
当使用 count ++
count
变量增加1;但从操作符返回的值是 count
变量的先前值。
When you use count++
, the count
variable is incremented by 1; but the value returned from the operator is the previous value of count
variable.
您可以通过尝试
public class Test {
public static void main(String[] args) {
int count = 0;
System.out.println(count++); // line 1
System.out.println(count++);
}
}
当您运行以上是结果。 p>
When you run above below is the results.
0
1
这是行1只打印 0
,因为 count ++
的返回值总是上一个值。
That is "line 1" prints only 0
since the return value of count++
is always the previous value.
这篇关于用于计算类的实例数量的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!