【发布时间】:2015-09-29 11:55:53
【问题描述】:
我正在阅读“Java - Herbert Schildt 的初学者指南”。我希望这个问题不会太荒谬。它是关于 while 循环条件的,其中 while 循环位于 for 循环内。代码示例是这样的:
public static void main(String[] args) {
int e;
int result;
for (int i = 0; i < 10; i++) {
result = 1;
e = i;
while (e > 0) {
result *= 2;
e--;
}
System.out.println("2 to the " + i + " power is " + result);
}
}
在while (e > 0)之后写的范围内,我不明白e的递减。由于 e = i,并且 i 递增,我相信在第一次执行 for 循环后 e 应该大于 0。如果 e 不递减,程序将无法正常运行。为什么在这个例子中需要递减 e?
【问题讨论】:
-
因为如果你不这样做,
while (e > 0)将总是评估为真,所以你将有一个无限循环。 -
If e is not decremented, the program will not run properly. Why is decrementing e necessary in this example?... 因为如果不递减程序将无法正常运行。你自己回答了这个问题。 -
如果在e递减后加上
System.out.println(e)运行代码,应该就清楚了。
标签: java while-loop conditional-statements