首页 > 解决方案 > 计数器方法不递增

问题描述

我正在做一个练习,我的主程序看起来像这样,它使用一个计数器类来打印一个数字列表,直到它达到我在创建对象时给出的限制,然后返回到 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;
  }

}

标签: javaclasscounterincrement

解决方案


你需要一个else

if (this.value <= upperLimit) {
    this.value+=1;
} else {
    this.value = 0;
}

推荐阅读