0

对于我的 Java 练习中期,我们需要编写一行代码的准确输出,在本例中是一个 for 循环。这是代码:

for(int first = 3; first > 0; first--)
        for(int second = --first; second <= 5; second++)
            System.out.println(first + " " + second);

所以我认为输出是:

2 2
2 3
2 4
2 5

但是当我在 Ecplipse 中运行它时,它会出现:

2 2
2 3
2 4
2 5
0 0
0 1
0 2
0 3
0 4
0 5

我了解“第二”如何从 5 变为 0,因为“第二 <= 5”,但我看不到“第一”如何也重置为 0。

我到处寻找答案,但找不到答案。任何关于它如何工作的帮助都会很棒。谢谢!

4

1 回答 1

3

你递减first了两次:每次外循环迭代一次,每次内循环开始迭代一次。

So after printing 2 5 it hits the end of the inner loop, and hits the first-- from the outer loop. Then as it goes back into the inner loop again, it hits int second = --first before printing anything else. Hence going from 2 to 0.

Personally I would try to avoid statements like int second = --first; - the side-effects often cause confusion.

于 2013-10-20T19:31:51.180 回答