这是我的嵌套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。
答案 0 :(得分:1)
让我为您当前的代码添加评论。按顺序执行步骤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"
。
答案 1 :(得分:0)
当涉及整数“e”的嵌套循环第一次运行时,c从1到6开始执行。退出此循环时'c'为6,因此“Hello world 1”将打印到控制台。然后,再次调用涉及'e'的循环,在退出循环之前将'c'再次加入11到11,这意味着下次第一个循环通过时'c'= 11,因为它是执行的每次运行内循环五次。
答案 2 :(得分:0)
您的输出已经回答了您的问题。请记住,Java完全按照您键入的顺序执行代码。让我们考虑一下代码的执行顺序:
c
从1开始。d
从0开始,跳过if
语句,因为没有条件为真。c
6。d
增加到1,if
语句打印出Hello World 1
。c
增加到11。d
会增加到2并跳过if
语句,因为c
既不是6也不是7。d
达到10。答案 3 :(得分:0)
请看以下循环:
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等。由于条件从未满足,因此消息没有打印。
答案 4 :(得分:0)
你可以在 -
之前删除else条件 else if (c ==7){
}
并且只写 -
if (c==7){}
因为在代码c
达到6时,它会跳过测试c==7