【发布时间】:2017-12-20 23:58:36
【问题描述】:
好吧,在尝试理解 while 循环的总体概念时,我遇到了这个..
public static void main (String[] args) {
int x = 1;
System.out.println("Before the loop");
while(x < 4) {
x = x + 1;
System.out.println("In the loop");
System.out.println("Value of loop x is " + x);
}
System.out.println("This is after the loop");
}
这里的输出是
Before the loop
In the loop
Value of loop x is 2
In the loop
Value of loop x is 3
In the loop
Value of loop x is 4
This is after the loop
当我这样改变语句的位置时,
public static void main (String[] args) {
int x = 1;
System.out.println("Before the loop");
while(x < 4) {
System.out.println("In the loop");
System.out.println("Value of loop x is " + x);
x = x + 1;
}
System.out.println("This is after the loop");
}
输出是,
Before the loop
In the loop
Value of loop x is 1
In the loop
Value of loop x is 2
In the loop
Value of loop x is 3
This is after the loop
请向我解释为什么仅通过更改该语句的位置,输出就会发生如此巨大的变化。
任何帮助将不胜感激......我是一个目标很高的学习者;)
【问题讨论】:
-
您正在打印
x的值,因此在 println 语句之前或之后增加x的值会有所不同。
标签: java loops while-loop conditional statements