Java – expect this loop to be infinite, but it’s not

This is my java code:

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

This is the output:

small x

I expect an infinite loop... Any idea why does it do this?

Solution

X start 5 Then when you cycle, it goes to 6, 7, 8, etc Eventually it will reach the maximum possible int. the next X = x 1 sets it to the most negative int, minus 2 billion - anyway This is less than 3, so the message is output Then execute the while condition again. Now it fails and exits the loop

Therefore, although it seems to be an infinite cycle, this is not the case

Is this a homework problem? Why did you write such strange code?

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>