我必须从一本带有 2 个 foor 循环和一个 if 语句的练习书中得到这段代码,我无法理解输出!所以我猜我不明白 for 循环是如何工作的
class Multifor {
public static void main(String[] args) {
for (int x = 0; x < 4; x++) {
for (int y = 4; y > 2; y--) {
System.out.println(x + " " + y);
}
if (x == 1) {
x++;
}
}
}
}
输出是:
0 4,
0 3,
1 4,
1 3,
3 4,
3 3,
第一个问题:如果在 for 循环中 x 每次代码运行到循环时都递增 1,那么当代码到达代码的 System.out.println 部分时,x 是怎么两次出现在输出上的 0它已经是 1 ,加上 if 语句中 1 的增量 if x == 1;这将使 x 2 的第二个输出。
第二个问题:如果y = 4,每次for循环都减1,怎么输出先3后4??等等,如果我没有看到 y 变量有任何增加?
最佳答案
First question: How came x is twice 0 on the output if in the for loop it is incremented by 1 every time the code runs into the loop,by the time the code reachs the System.out.println part of the code it is alredy 1 , plus the incrementation of 1 in the if statment if x == 1; which would make the second output of x 2.
每次您进入主 x
循环时,您的内部循环 y
循环两次。
此外,当您第一次进入循环时,x
的值是您在 for
声明中分配的值。
这就是为什么 x
的值在两次打印中只改变一次。
Second question:If y = 4 and it is decremented by 1 every time the for loop runs how is the output first 3 and then 4?? and so on if i don´t see any incrementation for the y variable?
y
的输出是 4 然后 3。
0 4
0 3
1 4
1 3
3 4
3 3
关于java - 与 for Loop 的输出混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32667946/