!= Java中的运算符循环

Ale*_*207 4 java loops for-loop

为什么以下代码打印"J的值是:1000"?
我会认为"j!= 1000"会在所有情况下评估为假(因为1000 mod 19不是0),因此使其成为无限循环.

public static void loop2() {
    int j = 0;

    for(int i=0;j != 1000;i++) {
        j = j+19;
    }
    System.out.println("The value of J is: " + j);
}
Run Code Online (Sandbox Code Playgroud)

Sah*_*heb 14

java中int的最大值是2,147,483,647在j上加19,一次又一次,这个值将被传递.之后它将从int的最小值再次开始-2,147,483,648.

这将持续到j的值在某个时刻变为1000.因此,循环将停止.

j将在整数的最大值上迭代17次以达到此点.检查代码:

public class Solution {
    public static void main(String args[]) {
        int j = 0;
        int iterationCount = 0;

        for(int i=0;j != 1000;i++) {
            j = j+19;
            if(j - 19 > 0 && j < 0) {
                iterationCount ++;
            }

        }
        System.out.println("The value of J is: " + j + " iterationCount: " + iterationCount);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

The value of J is: 1000 iterationCount: 17
Run Code Online (Sandbox Code Playgroud)

  • 作为旁注,它会溢出并再次循环~17次,然后才达到1000. (3认同)