public class apples {
    public static void main(String[] args) {
        int beerNum = 99;
        String word = "bottles";

        while (beerNum > 0) {

            if (beerNum == 1) {
                word = "bottle"; // ONE bottle
            }

            System.out.println(beerNum + " " + word + " of beer on the wall, " + beerNum + " " + word + " of beer");
            beerNum = beerNum - 1;

            if (beerNum > 0) {
                System.out.println("Take one down, pass it round " + beerNum + " " + word + " of beer");
            }
        }

        if (beerNum == 0) {
            System.out.println("No more bottles of beer");
        }

    }
}

输出为:
99 bottles of beer on the wall, 99 bottles of beer
Take one down, pass it round 98 bottles of beer
98 bottles of beer on the wall, 98 bottles of beer
Take one down, pass it round 97 bottles of beer
97 bottles of beer on the wall, 97 bottles of beer
Take one down, pass it round 96 bottles of beer
96 bottles of beer on the wall, 96 bottles of beer
Take one down, pass it round 95 bottles of beer
95 bottles of beer on the wall, 95 bottles of beer...

(And so on and so forth)

3 bottles of beer on the wall, 3 bottles of beer
Take one down, pass it round 2 bottles of beer
2 bottles of beer on the wall, 2 bottles of beer
Take one down, pass it round 1 bottles of beer
1 bottle of beer on the wall, 1 bottle of beer
No more bottles of beer

为什么String单词不等于“bottle”?取而代之的是,在“放下一瓶,将其倒入1瓶啤酒中”中显示“瓶”。

同样在“一瓶啤酒在墙上,一瓶啤酒”之后,也没有说“顺着一圈过去”

Link to the lyrics

最佳答案

只需将您编写的这段代码减去瓶号而不是之前的代码

if (beerNum == 1) {
    word = "bottle"; //ONE bottle
}

所以你的代码将是
public class apples {
    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, " + beerNum + " " + word + " of beer");
            beerNum = beerNum - 1;

            if (beerNum == 1) {
                word = "bottle"; //ONE bottle
            }

            if (beerNum > 0) {
                System.out.println("Take one down, pass it round " + beerNum + " " + word + " of beer");
            }
        }

        if (beerNum == 0) {
            System.out.println("No more bottles of beer");
        }
    }
}

关于java - 尝试编码99瓶啤酒之歌,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32576203/

10-10 13:56