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();
    }
}
4

3 回答 3

5

首次运行时,您的循环条件不太可能为真:

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

也就是说,为了执行循环,n必须是0. 鉴于您正在背诵“墙上有 N 瓶啤酒”,这似乎不正确。

你打算写的是n必须大于或等于0。

for(n = numBeerBottles; n >= 0; n--)
于 2013-10-04T06:29:57.260 回答
4

我怀疑你for-loop设置不正确...

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

它基本上是说,for n = numBeerBottles, while n == 0do n--...

尝试...

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

反而...

于 2013-10-04T06:30:42.423 回答
2

我认为在这种情况下,while 循环更直观,动词适合你用英语说的内容

n = numBeerBottles;
while (n >= 0) 
{
// code
   n--;
 }
于 2013-10-04T06:34:24.297 回答