【问题标题】:counter method not incrementing计数器方法不递增
【发布时间】: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


【解决方案1】:

你需要一个else

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

【讨论】:

    【解决方案2】:

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

    修改代码:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 2019-04-05
      • 2021-05-22
      • 2014-08-01
      • 1970-01-01
      相关资源
      最近更新 更多