gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:38:51 25 4
gpt4 key购买 nike

这是我的嵌套 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。

最佳答案

让我向您当前的代码添加注释。按顺序执行步骤 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" 永远不会被打印。

关于java - 为什么我的嵌套 for 循环不显示 Hello World 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34979818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com