简体   繁体   中英

Why does this nested for loop loops infinitely (java)?

public class test {
    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            System.out.println(i);

            for (i = 0; i < 1; i++) {
                System.out.println(i);
            }
        }
    }
}

You are using the same loop variable i for both the outer and the inner loops.

The inner loop resets i to 0 and increments it to 1 , and then the outer loop increments it to 2 , but it can never get higher than 2 (since the next time the inner loop executes, it will be reset to 0 again), so the outer loop never ends.

Use a different variable for the inner loop:

for (int i = 0; i < 3; i++) {
    System.out.println(i);
    for (j = 0; j < 1; j++) {
        System.out.println(j);
    }
}

Your inner for loop has same variable use that is used in your outer for loop so it goes to infinite loop, make change on inner for loop just put int front of j .

for (int j = 0; j < 1; j++) {
    System.out.println(j);
}

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