啤酒瓶歌谣

这篇博客分析了一个用Java编写的啤酒瓶歌谣程序,探讨了程序的运行逻辑和控制结构。作者注意到在99个瓶子时,歌谣的表述只出现了一次,与其它情况不同,并分享了对此现象的想法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

分析

整个程序最后呈现出来的效果,应该是童谣一样,xx个瓶酒在墙上,要说两遍,之后“拿下来,传下去”。如果是结束的时候就不用说两遍了,直接说没有,然后循环结束。结束的控制条件是beerNum为0。所以需要循环和控制语句。

想法

程序跑出来我会觉得有一点奇怪,99个瓶子的时候“xx个啤酒在墙上”只说了一次。代码中开头和最后的判断都要输出一次才构成了两次,结果第一次和最后一次就比较不一样。我的想法如下:

public class BeerSong {
    public static void main(String[] args) {
        int beerNum = 99;
        String word = "bottles";
        while (beerNum > 0) {
            if (beerNum == 1) {
                // 啤酒瓶只剩下一个,瓶子变成单数
                word = "bottle";
            }
            System.out.println(beerNum + " " + word + " " + "of beer on the wall");
            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.");

            if (beerNum -1 ==  0) {
                System.out.println("No more bottles of beer on the wall.");
            }
            beerNum--;
        }
    }
}
运行结果如下
99 bottles of beer on the wall
99 bottles of beer on the wall
99 bottles of beer.
Take one down.
Pass it around.
98 bottles of beer on the wall
98 bottles of beer on the wall
98 bottles of beer.
Take one down.
Pass it around.
.
.
.

3 bottles of beer on the wall
3 bottles of beer on the wall
3 bottles of beer.
Take one down.
Pass it around.
2 bottles of beer on the wall
2 bottles of beer on the wall
2 bottles of beer.
Take one down.
Pass it around.
1 bottle of beer on the wall
1 bottle of beer on the wall
1 bottle of beer.
Take one down.
Pass it around.
No more bottles of beer on the wall.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值