简体   繁体   中英

Not receiving correct output for the following nested for loop

I need an explanation for the following loop:

    public static void main(String[] args) {
    int x = 0;
    int y = 30;

for (int outer = 0; outer < 3; outer++) {
    for (int inner = 4; inner > 1; inner--) {
        x = x + 6; 
        y = y - 2; 
        if (x == 6) {
            break;
        }
        x = x + 3;
    }
    y = y - 2;
}

System.out.println(x + " " + y);
}

The way I'm seeing it is that the 'outer' loop is running 3 times and the 'inner' loop is running 9 times. When I go through the 'inner' loop, x becomes 6, and we break out of the 'inner' loop after we get the value for y , which is 28. So now, the value of x is 6, and now I go through the 'outer' loop which runs 3 times, so 3 times 2 is equal to 6, so I subtract that from 28, and I end up with 22.

Output:

6 22

Does anyone know what I am doing wrong? I know the output should be 60 10 , but I am not getting this. Thanks for your help.

I have copied and pasted your code in my pc and I get the out put 60 10 I think your are running a different file in your IDE. What IDE do you use?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM