分析
整个程序最后呈现出来的效果,应该是童谣一样,xx个瓶酒在墙上,要说两遍,之后“拿下来,传下去”。如果是结束的时候就不用说两遍了,直接说没有,然后循环结束。结束的控制条件是beerNum为0。所以需要循环和控制语句。
想法
程序跑出来我会觉得有一点奇怪,99个瓶子的时候“xx个啤酒在墙上”只说了一次。代码中开头和最后的判断都要输出一次才构成了两次,结果第一次和最后一次就比较不一样。我的想法如下:
public class BeerSong {
public static void main(String[] args) {
int beerNum = 99;
String word = "bottles";
while (beerNum > 0) {
if (beerNum == 1) {
// 啤酒瓶只剩下一个,瓶子变成单数
word = "bottle";
}
System.out.println(beerNum + " " + word + " " + "of beer on the wall");
System.out.println(beerNum + " " + word + " " + "of beer on the wall");
System.out.println(beerNum + " " + word + " " + "of beer.");
System.out.println("Take one down.");
System.out.println("Pass it around.");
if (beerNum -1 == 0) {
System.out.println("No more bottles of beer on the wall.");
}
beerNum--;
}
}
}
运行结果如下
99 bottles of beer on the wall
99 bottles of beer on the wall
99 bottles of beer.
Take one down.
Pass it around.
98 bottles of beer on the wall
98 bottles of beer on the wall
98 bottles of beer.
Take one down.
Pass it around.
.
.
.
3 bottles of beer on the wall
3 bottles of beer on the wall
3 bottles of beer.
Take one down.
Pass it around.
2 bottles of beer on the wall
2 bottles of beer on the wall
2 bottles of beer.
Take one down.
Pass it around.
1 bottle of beer on the wall
1 bottle of beer on the wall
1 bottle of beer.
Take one down.
Pass it around.
No more bottles of beer on the wall.