期望这个循环是无限的,但事实并非如此

har*_*ari 3 java

这是我的Java代码:

public class Prog1 {
    public static void main(String[] args) {
        int x = 5;
        while (x > 1) { 
            x = x + 1;
            if (x < 3)
                System.out.println("small x");   
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是输出:

small x
Run Code Online (Sandbox Code Playgroud)

我期待一个无限循环...任何想法为什么它这样做?

Geo*_*nis 6

有一个无限循环.只是在某个时候,x得到了一点,它溢出了一个有符号的int的限制,并且它变为负数.

public class Prog1 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int x = 5;
        while (x > 1) { 
            x = x + 1;
            System.out.println(x);
            if(x < 3)
                System.out.println("small x");   
        }
    }
}
Run Code Online (Sandbox Code Playgroud)