2013-10-04 85 views
0

該程序只是在牆上輸出歌曲九十九瓶啤酒。它編譯沒有錯誤,但在我的代碼中沒有任何反應。我認爲這與我爲最後兩種方法設置參數有關,而我的實例變量卻對此有所瞭解。我很困惑爲什麼我的程序沒有循環和打印

package beersong; 

public class BeerSong 

{ 
    private int numBeerBottles; 
    private String numberInWords; 
    private String secondNumberInWords; 
    private int n; 

    private String[] numbers = {"", "one", "two", "three", "four", "five", 
     "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", 
     "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" 
    }; 

    private String[] tens = {"", "", "Twenty", "Thirty", "Forty", "Fifty", 
     "Sixty", "Seventy", "Eighty", "Ninety" 
    }; 

    //constructor 
    public BeerSong (int numBeerBottles) 
    { 
     this.numBeerBottles = numBeerBottles; 
    } 

    //method to return each line of song 
    public String convertNumberToWord(int n) 
    { 
     if(n<20) 
     { 
      this.numberInWords = numbers[n]; 
     } 

     else if (n%10 == 0) 
     { 
      this.numberInWords = tens[n/10]; 
     } 

     else 
     { 
      this.numberInWords = (tens[(n - n%10)] + numbers[n%10]); 
     } 

     return this.numberInWords; 
    } 

    //method to get word for n-1 beer in song 
    public String getSecondBeer(int n) 
    { 
     if((n-1)<20) 
     { 
      this.secondNumberInWords = numbers[(n-1)]; 
     } 

     else if ((n-1)%10 == 0) 
     { 
      this.secondNumberInWords = tens[(n-1)/10]; 
     } 

     else 
     { 
      this.secondNumberInWords = (tens[((n-1) - (n-1)%10)] + numbers[(n-1)%10]); 
     } 
     return this.secondNumberInWords; 
    } 

    //method to actually print song to screen 
    public void printSong() 
    { 
     for (n=numBeerBottles; n==0; n--) 
     { 
     System.out.println(convertNumberToWord(n) + " bottles of beer on the " 
       + "wall. " + convertNumberToWord(n) + " bottles of beer. " 
       + "You take one down, pass it around " 
       + getSecondBeer(n) + " bottles of beer on the wall"); 
     System.out.println(); 
     } 
    } 

    public static void main(String[] args) 
    { 
     BeerSong newsong = new BeerSong(99); 
     newsong.printSong(); 
    } 
} 
+0

n ==可0說什麼必須N> = 0 :) – Raja

回答

5

你的循環條件不太可能是真的時,它的首次運行:

for(n=numBeerBottles; n==0; n--) 

,說,爲了要執行的循環,n必須0這看起來不正確,因爲你正在背誦「N瓶啤酒在牆上」。

什麼你打算寫的是n必須大於或等於0

for(n = numBeerBottles; n >= 0; n--) 
4

我懷疑你for-loop設置錯誤...

for (n=numBeerBottles; n==0; n--) 

這是基本上說,對於n = numBeerBottles,而n == 0n-- ...

嘗試...

for (n=numBeerBottles; n >= 0; n--) 

,而不是...

2

我認爲在這種情況下,while循環更加直觀和動詞適合你的英文

n = numBeerBottles; 
while (n >= 0) 
{ 
// code 
    n--; 
}