3

我对 JAVA 编程非常陌生,以前只用 Python 编程过。当我执行我的代码时,我试图弄清楚为什么我会得到重复的“墙上的啤酒瓶数”行。

    package BeerBottle;

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

      while (beerNum > 0) {

      if (beerNum == 1) {
      word = "bottle";
      } else {
      word = "bottles";
      }
    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");
    beerNum = beerNum -1;

    if (beerNum > 0) {
        System.out.println(beerNum + " " + word + " " + "of beer on the wall"); // I think it might be this line but I need it 
    } else {
        System.out.println("No more bottles of beer on the wall");
    }
    }
   }

}

我得到的结果是这样的:

    2 bottles of beer on the wall
    2 bottles of beer on the wall (duplicate)
    2 bottles of beer
    Take one down
    pass it around
    1 bottles of beer on the wall
    1 bottle of beer on the wall (duplicate)
    1 bottle of beer
    Take one down
    pass it around
    No more bottles of beer on the wall

谢谢您的帮助

4

3 回答 3

5

循环的最后一个打印行与下一个循环的第一个打印行相同,所以这不是问题。要直观地分离每个循环的输出,请在方法的最后打印一个空行。然后你会看到这样的东西:

2 bottles of beer on the wall  // Last line of a loop

2 bottles of beer on the wall  // First line of the next loop
2 bottles of beer
Take one down
pass it around
1 bottles of beer on the wall  // Last line of a loop

1 bottle of beer on the wall   // First line of next loop
1 bottle of beer
Take one down
pass it around
No more bottles of beer on the wall
于 2013-07-26T22:40:54.250 回答
2

你确定你实际上得到了一个意外的重复行,并且没有将一个节的最后一行误认为下一个节的第一行吗?尝试在每个节的末尾添加一个额外的空行以清楚地看到差异。

这可以通过额外的 System.out.println("") 或在前一个末尾添加“\n”来完成。

此外,一旦减少啤酒的数量,您将需要重新评估您正在使用的啤酒词。

于 2013-07-26T22:42:05.140 回答
0

我会使用for循环而不是while. 我可以在最后两次迭代中摆脱循环,这必须处理“瓶子/瓶子”的东西。

我的循环将如下所示:

for (int num_beers=99; i>2; i--) {
  String output = num_bers + " bottles of beer";

  System.out.println(output + " on the wall");
  System.out.println(output);
  System.out.println("Take one down\npass it around");
  System.out.println(output.replace(num_beers, num_beers-1) + " on the wall");
}

使用该循环,最后打印的字符串将是“墙上有 2 瓶啤酒”(第一次)。

只是为了练习,做同样的例子但使用递归方法会很好

于 2013-07-26T23:12:19.633 回答