关于while语句
public class BeerSong {
public static void main(String[] args){
int x = 99;
while(x <100){
System.out.println("Beer :" + x);
x = x - 1;
}
if(x == 0){
System.out.println("BeerSong Game Over!");
}
}
}

执行结果说:Too much output process。
我本来是想写一个从99数到0的代码,结果,没完没了的输出。原因是我没理解while的真正含义。
while的意思是当满足xxx的时候,做xxx事。
对while的条件进行修改
public class BeerSong {
public static void main(String[] args){
int x = 99;
while( x >= 0){
System.out.println("Beer :" + x);
x = x - 1;
}
if(x == 0){
System.out.println("BeerSong Game Over!");
}
}
}
输出结果:从99,执行到0。

但是,没有输出“Game over”,为什么?
我前面想要x一直输出到0,输出到0后,由于while的条件包含了=0,所以还会继续执行循环,在循环里会是-1。所以执行到if的时候x会变成-1,就没办法输出Game over啦。
public class BeerSong {
public static void main(String[] args){
int x = 99;
while( x > 0){ //while的意思是当xxx的时候做xxx事
System.out.println("Beer :" + x);
x = x - 1;
}
if(x == 0){
System.out.println("BeerSong Game Over!");
}
}
}
输出结果:

Game over有了,数字0没有了。
浙公网安备 33010602011771号