为什么我的整数增加2而不是1?java的

Cad*_*ade 1 java int increment while-loop

我已经实现了类似于简单时钟的代码,每次在我的课程中它应该增加1.到目前为止,这是我在主程序中的内容:

public static void main(String[] args) {
    BoundedCounter counter = new BoundedCounter(60);
    System.out.println("Value at start: " + counter);
    int i = 0;
    while (i < 10) {
        counter.next();
        System.out.println("Value: " + counter);
        i++;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是"BoundedCounter"类:

class BoundedCounter {

    private int value;
    private int upperBound;

    public BoundedCounter(int upperBound) {
        this.upperBound = upperBound;
        this.value = 0;  
    }

    public void next () {
        if (value++ > upperBound) { 
            value = 0;
        } else {
            value++;
        }
    }

    public String toString() {
        return "" + value;
    }
}
Run Code Online (Sandbox Code Playgroud)

此代码的输出是:

Value at start: 0
Value: 2
Value: 4
Value: 6
Value: 8
Value: 10
Value: 12
Value: 14
Value: 16
Value: 18
Value: 20
Run Code Online (Sandbox Code Playgroud)

我不明白为什么它会增加2,而在课堂上,while语句有value++; 这意味着它应该增加1.

我在这里错过了什么?

Ell*_*sch 11

你的if执行value++然后(假设else输入)你再次执行.更改

if (value++ > upperBound) { 
    value = 0;
} else {
    value++;
}
Run Code Online (Sandbox Code Playgroud)

喜欢的东西

if (value + 1 > upperBound) { 
    value = 0;
} else {
    value++;
}
Run Code Online (Sandbox Code Playgroud)

要么

if (value < upperBound) {
    value++;
} else {
    value = 0;
}
Run Code Online (Sandbox Code Playgroud)

  • (或删除其他). (4认同)
  • (或者`if(value> = upperBound)`) (3认同)
  • `if(value> = upperBound)`是一种更安全的写入方式,因为它避免了`upperBound == Integer.MAX_VALUE`时的整数溢出问题. (3认同)