英文:
Trying to count the amount of objects created
问题
我在创建 x 个对象之前和之后,两个计数器都一直得到 0。
class Thing {
private static int count = 0;
public Thing() {
count++;
}
public static int getCount(){
return count;
}
}
public class getCounter {
public static void main(String[] args) {
int counter = Thing.getCount();
System.out.println("已创建的对象数:" + counter);
Thing thing1 = new Thing();
Thing thing2 = new Thing();
System.out.println("已创建的对象数:" + Thing.getCount());
}
}
英文:
I keep getting 0 for both counters before and after creating x amount of objects.
class Thing {
private static int count = 0;
public Thing() {
count++;
}
public static int getCount(){
return count;
}
}
public class getCounter {
public static void main(String[] args) {
int counter = Thing.getCount();
System.out.println("Objects created: " + counter);
Thing thing1 = new Thing();
Thing thing2 = new Thing();
System.out.println("Objects created: " + counter);
}
}
答案1
得分: 4
你需要再次调用getCount()
以获取更新后的计数。如果你将它缓存在一个变量中,你将始终获得相同的值。
public static void main(String[] args) {
System.out.println("创建的对象数:" + Thing.getCount());
Thing thing1 = new Thing();
Thing thing2 = new Thing();
System.out.println("创建的对象数:" + Thing.getCount());
}
英文:
You need to call getCount()
again to get an updated count. If you cache it in a variable you'll always have the same value.
public static void main(String[] args) {
System.out.println("Objects created: " + Thing.getCount());
Thing thing1 = new Thing();
Thing thing2 = new Thing();
System.out.println("Objects created: " + Thing.getCount());
}
答案2
得分: 0
只是在John的正确答案上补充并解释 - 为什么他的答案是正确的:
将值赋给变量,就是在执行的特定时间将该值存储在该变量中。
例如:
int x = Math.sqrt(25);
意味着将由Math.sqrt(25)
返回的值(即5)存储到变量x
中。
你将从getCount()
获得的值存储在局部变量counter
中,但你从未更新它,而且无论你创建了多少个对象,如果counter
变量保持不变,它的值始终为0
。
在构造函数更新类成员counter
两次之后,你可能希望再次调用getCount()
以检索最新的值。
英文:
Just to add on John's correct answer and explain - why his answer is correct:
Assignment of the value to the variable, is storing that value in that variable at a particular time of execution.
For example:
int x = Math.sqrt(25);
Means to store the value returned by Math.sqrt(25)
(which is 5), into variable x
.
You store the value returned from getCount()
in the local variable counter
, but you never update it, and disregarding of how many objects you'll create, if counter
variable remains like it is, it will always have the same value 0
.
After your constructor updates the class member counter
twice, you might want to call getCount()
again to retrieve the up to date value.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论