【发布时间】:2018-06-10 15:07:49
【问题描述】:
我正在做一个练习,我的主程序看起来像这样,它使用一个计数器类来打印一个数字列表,直到它达到我在创建对象时给出的限制,然后返回到 0。 我期待它返回 0,1,2,3,4,5 然后循环回到 0 但它所做的一切都给了我 0。
public class Main {
public static void main(String args[]) {
BoundedCounter counter = new BoundedCounter(5);
System.out.println("value at start: "+ counter);
int i = 0;
while (i< 10) {
counter.next();
System.out.println("Value: "+counter);
i++;
}
}
}
我的 BoundedCounter 类看起来像这样;
public class BoundedCounter {
private int value;
private int upperLimit;
public BoundedCounter(int Limit) {
upperLimit = Limit;
}
public void next(){
if (this.value <= upperLimit) {
this.value+=1;
}
this.value = 0;
}
public String toString() {
return "" + this.value;
}
}
【问题讨论】:
-
您的
next方法总是 将value设置为0 -
尝试调试你的程序,看看在
next方法中哪一行this.value设置为0。 -
(注意:这不是 Python。大多数时候你不需要
this.。)
标签: java class counter increment