墙上的99瓶啤酒 - 减法循环

时间:2018-03-07 08:25:04

标签: java

我需要这首歌从99到0唱出来。但是当我得到1瓶时,我需要将它格式化为正确的方式。我尝试使用if语句并且它可以工作,但它不会让我从循环中完成它的事情。循环第一次到达时,格式就搞砸了。

public class Example1 {

  public static void main(String[] args) {
    int counter = 99;
    int sum = 0;
    while (counter < 100 && counter > 0) {
      if (counter >= 2) {
        System.out.println(
            counter + " bottles of Pepsi on the wall, " + counter + " bottles of Pepsi.");
        System.out.println(
            "Take one down, pass it around, " + (counter - 1) + " bottles of Pepsi on the wall.");
        counter--;
        if (counter == 1) {
          System.out.println("1 bottle of Pepsi on the wall, 1 bottle of Pepsi.");
          System.out.println("Take one down, pass it around, 0 bottles of Pepsi on the wall.");
          counter--;
        }
      }
    }
  }
}

最后需要在输出上看起来像这样。

2 bottles of Pepsi on the wall, 2 bottles of Pepsi.\n
Take one down, pass it around, 1 bottle of Pepsi on the wall.\n
1 bottle of Pepsi on the wall, 1 bottle of Pepsi.\n
Take one down, pass it around, 0 bottles of Pepsi on the wall.\n

现在它输出就像这样。

Take one down, pass it around, 2 bottles of Pepsi on the wall.
2 bottles of Pepsi on the wall, 2 bottles of Pepsi.
Take one down, pass it around, 1 bottles of Pepsi on the wall.
1 bottle of Pepsi on the wall, 1 bottle of Pepsi.
Take one down, pass it around, 0 bottles of Pepsi on the wall.

任何帮助将不胜感激。感谢。

1 个答案:

答案 0 :(得分:1)

如果你拿出使n bottle(s)成为单独方法的代码会更容易。

private static String nBottles(int n) {
    return "" + n + " bottle" + (n != 1 ? "s" : "");
}

public void test(String[] args) throws Exception {
    int counter = 99;
    while (counter < 100 && counter > 0) {
        System.out.println(nBottles(counter) + " of Pepsi on the wall, " + nBottles(counter) + " of Pepsi.");
        counter--;
        System.out.println("Take one down, pass it around, " + nBottles(counter) + " of Pepsi on the wall.");
    }
}