2016-07-26 103 views
-1
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 

這段代碼打印出:如果while循環中

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'語句_isn't_。它在循環內部。 – khelwood

+0

你的代碼有什麼問題?這看起來是正確的,儘管它不像你想要的那樣打印,正如Andy Turner已經指出的那樣。改變你的第三和第四個打印語句('System.out.println(「Take one down。」);''和'System.out.println(「Pass it around。」);')to'System.out.print 「拿下一個並傳遞給它,」);'你應該幾乎完成。 – Thomas

回答

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"); 
    } 
} 
} 
+0

如果沒有啤酒,你可以在牆上寫'0瓶啤酒',這是如何改善的? –

+0

這種情況似乎是正確的。如果'beerNum'是0(即它不大於0 - else分支),他想打印「沒有更多瓶啤酒在牆上」。你的修復會打破。 – Thomas

+0

謝謝,一個noobie錯誤哈哈 – user6640454