简体   繁体   English

为什么这个嵌套的 for 循环无限循环(java)?

[英]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.您对外循环和内循环使用相同的循环变量i

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.内循环将i重置为0并将其递增为1 ,然后外循环将其递增为2 ,但它永远不会高于2 (因为内循环下次执行时,它将再次重置为0 ),所以外循环永远不会结束。

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 循环具有与外部 for 循环中使用的变量相同的变量用途,因此它进入无限循环,对内部 for 循环进行更改,只需将int放在j前面。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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