为什么我的嵌套 for 循环不显示 Hello World 2



这是我嵌套的循环。

int c = 1;
for (int d = 0; d < 10; d++) {
    if (c == 6) {
        System.out.println("Hello World 1");
    } else if (c == 7) {
        System.out.println("Hello World 2");
    }
    for (int e = 0; e < 5; e++) {
        System.out.println("This is the nested for loop :" +c);
        c++;
    }
}

这是我的控制台正在打印的内容。

This is the nested for loop :1
This is the nested for loop :2
This is the nested for loop :3
This is the nested for loop :4
This is the nested for loop :5
Hello World 1
This is the nested for loop :6
This is the nested for loop :7
This is the nested for loop :8

它继续打印它,直到达到 50 并且不显示 Hello World 2。

让我为您当前的代码添加注释。按顺序执行步骤 1 到 7 来阅读此代码。

int c = 1;
for (int d = 0; d < 10; d++) {
    // 1. When we are here for the first time, c = 1, both if are false
    // 4. Now, c is equal to 6 so the first if is true, "Hello World 1" is printed
    // 7. Now, c is equal to 11, both if are false, nothing is printed...
    if (c == 6) {
        System.out.println("Hello World 1");
    } else if (c == 7) {
        System.out.println("Hello World 2");
    }
    for (int e = 0; e < 5; e++) {
        // 2. We reach here, c is incremented 5 times.
        // 5. c is incremented again 5 times
        System.out.println("This is the nested for loop :" +c);
        c++;
    }
    // 3. When we're here, c that was 1 is now 6 (incremented 5 times in step 2)
    // 6. When we're here for the second time, c is now 11 (6 incremented 5 times in step 5)
}

基本上,在第一个for的开头,c是 1,然后是 6,然后是 11......但从不打印 7,所以"Hello World 2"永远不会打印。

当涉及整数"e"的嵌套循环第一次运行时,c 从 1 到 6 表示。退出此循环时,"c"为 6,因此"Hello world 1"将打印到控制台。然后,再次调用涉及"e"的循环,在退出循环之前再向"c"发出五次,直到 11,这意味着下一次第一个循环运行时"c"= 11,因为它每次运行内部循环都会被指控五次。

您的输出已经回答了您的问题。请记住,Java 完全按照您键入代码的顺序执行代码。让我们考虑一下代码的执行顺序:

  1. c从 1 开始。
  2. d从 0 开始,并且跳过 if 语句,因为所有条件都不为真。
  3. 嵌套的循环增量c 6。
  4. d递增为 1,if语句将打印出Hello World 1
  5. 嵌套的循环增量c 11。
  6. d递增为 2,并且跳过 if 语句,因为c既不是 6 也不是 7。
  7. 执行一直持续到 d达到 10。

您可以在之前删除 else 条件 -

 else if (c ==7){
    }

和写,只有——

if (c==7){}

因为在代码中,当c达到 6 时,它会跳过测试c==7

请看下面的循环:

for (int e = 0; e < 5; e++) {
        System.out.println("This is the nested for loop :" +c);
        c++;
}

对于外循环的 10 次迭代中,每次将 c 递增 5 倍。这意味着当 if 语句检查 c = 7 时,它将是 1、6、11、16 等。由于从不满足条件,因此不会打印消息。

最新更新