我试图按照我的代码显示99瓶啤酒歌曲我没有得到else语句,程序应该有while和if语句,else语句虽然可能包含也可能不包括
public class bottles {
public static void main(String... s){
int beer = 99;
while(beer>=1){
if(beer>1){
System.out.print(beer + "bottles of beer on the wall ");
System.out.println(beer + "bottles of beer ");
System.out.print("Take one down and pass it around ");
beer = beer-1;
System.out.println(beer + "bottles of beer on the wall ");
}
if(beer==1){
System.out.print(beer + "bottles of beer on the wall ");
System.out.println(beer + "bottles of beer ");
System.out.print("Take one down and pass it around ");
System.out.println("no more bottles of beer on the wall. ");
System.out.println("");
}
else{
System.out.println("No more bottles of beer on the wall, no more bottles of beer.");
System.out.println("Go to the store and buy some more, 99 bottles of beer on thewall");
}
}
}
}
输出没有采用else语句。 java中的新手
答案 0 :(得分:0)
因为你的循环只能运行while(beer>=1)
答案 1 :(得分:0)
while
循环将执行,直到您再没有啤酒。
这意味着它最后一次执行是剩下1啤酒。
您的else
语句永远不会被执行。
所以只需将System.out.println("No more...
放在while
语句下(不包含else
):
while( more than 0 beer) {
do sth...
}
// No more beers left
print "no more beers left";
答案 2 :(得分:0)
你的其他人永远不会跑,好像啤酒> 1你的第一个如果有效,如果啤酒== 1,它会啤酒 - ,所以啤酒的价值== 0,你就不在你的圈子里了。比较值是从99到0不等。
条件:
1:值> 1和< 99:首先,如果值接受并继续减少
2:值达到:1,如果为你处理它,则为2,啤酒 - == 0;
3:value == 0,beer(0)> = 1为false所以你没有循环,而没有执行。所以你的其他东西从未通过代码
到达 while(beer>=1) //will run only if beer>=1
{
if(beer>1)
{ //execute if beer>1
beer -- // this will work till beer>1
}
if(beer==1)
{ //if beer==1 , this will execute
beer-- // val of beer==0 ,So next time loop does't work
}
else{ // will be never called, if beer==0 you will never reach inside while so this never executes
}
}
}
答案 3 :(得分:-1)
这是代码尝试这个
public static void main(String... args)
{
int beer = 10;
while(beer>=1){
if(beer>1){
System.out.print(beer + "bottles of beer on the wall ");
System.out.println(beer + "bottles of beer ");
System.out.print("Take one down and pass it around ");
beer = beer-1;
System.out.println(beer + "bottles of beer on the wall ");
}
if(beer==1){
System.out.print(beer + "bottles of beer on the wall ");
System.out.println(beer + "bottles of beer ");
System.out.print("Take one down and pass it around ");
System.out.println("no more bottles of beer on the wall. ");
System.out.println("");
}
else{
System.out.println("No more bottles of beer on the wall, no more bottles of beer.");
System.out.println("Go to the store and buy some more, 99 bottles of beer on thewall");
}
beer--;
}
}