public class BeerSong {
public static void main(String[] args) {
int beerNum = 99;
String word = "bottles";
while (beerNum > 0) {
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.");
beerNum = beerNum - 1;
if (beerNum == 1) {
word = "bottle"; // singular, as in ONE bottle.
}
if (beerNum > 0) {
System.out.println(beerNum + " " + word + " of beer on the wall");
} else {
System.out.println("No more bottles of beer on the wall");
} // end else
} // end while loop
} // end main method
} // end class
此代码打印出来:
99 bottles of beer on the wall
99 bottles of beer on the wall.
99 bottles of beer.
Take one down and pass it around.
为什么不这样打印:
99 bottles of beer on the wall
99 bottles of beer.
Take one down and pass it around, 99 bottles of beer on the wall.
因为if语句在循环之后
答案 0 :(得分:0)
这种情况正在破坏代码:
if (beerNum > 0) {
System.out.println(beerNum + " " + word + " of beer on the wall");
} else {
System.out.println("No more bottles of beer on the wall");
} // end else
如果数字不为零,你正在检查瓶子并打印......
你应该用以下内容替换那个逻辑:
if (beerNum == 0) {
System.out.println(beerNum + " " + word + " of beer on the wall");
}
之后,这首歌会很好地播放:)
最终代码可能如下:
public static void main(String[] args) {
int beerNum = 99;
String word = "bottles";
while (beerNum > 0) {
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.");
beerNum = beerNum - 1;
if (beerNum == 1) {
word = "bottle"; // singular, as in ONE bottle.
} else if (beerNum == 0) {
word = "bottles";
System.out.println(beerNum + " " + word + " of beer on the wall");
}
}
}