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

Why is my nested for loop not displaying Hello World 2

这是我的嵌套 for 循环。

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。

当嵌套循环涉及整数 "e" 运行s 到第一次时,c 从 1 递增到 6。'c' 在退出此循环时为 6,因此 "Hello world 1" 打印到控制台。然后,再次调用涉及 'e' 的循环,在循环退出之前再调用 'c' 五次直到 11,这意味着下一次 'c' = 11 第一次循环 运行 s through,因为它在每个 运行 内部循环中被增加了五次。

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

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

看下面的循环:

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 等。作为条件不见面,不打印消息

让我为您当前的代码添加注释。通过按顺序执行步骤 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"

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

 else if (c ==7){
    }

只写 -

if (c==7){}

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