このプログラムは、壁に 99 本のビールの歌を出力するだけです。エラーなしでコンパイルされますが、私のコードでは何も起こりません。最後の 2 つのメソッドのパラメーターとインスタンス変数の設定方法に関係があると思いますが、これを理解するのに苦労しています。
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();
}
}