计数器方法不递增

counter method not incrementing

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

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;
  }

}

您需要 else:

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

您需要将 this.value = 0 放在 else 语句中,因为它每次都会被执行。

修改后的代码:

public void next(){
    if (this.value <= upperLimit) {
        this.value+=1;

    }
    else
        this.value = 0;
}