【问题标题】:Java while and if and elseJava while 和 if 和 else
【发布时间】:2013-04-11 06:20:46
【问题描述】:
public class Head1 {
  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");
      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");
      }
      if (beerNum == 1) {
        System.out.println(beerNum + " " + word + " of beer on the wall");
      } else {
        System.out.println("No more bottles of beer on the wall!");
      }
    }
  }
}

这个来自 Java 书籍的示例代码打印出从 99 瓶啤酒到墙上没有啤酒瓶的歌曲。问题是当它是 1 瓶啤酒在墙上时,它仍然说瓶子。我试图通过在末尾添加if (beerNum == 1) 部分来解决此问题。但是,它仍然在墙上显示 1 瓶啤酒,我在墙上有一瓶啤酒。

我不知道要改变什么来解决这个问题。我要创建另一个 while 部分吗?

如果你能给他们一个提示,我可以自己解决,那也太酷了!因为我明白我的实际歌曲输出在第一个 if 部分,但我不知道我应该在哪里编辑“if”或者我是否应该创建另一个 if 部分。

谢谢!

【问题讨论】:

  • 这个问题说明缺乏基本的java知识...
  • 这就是我学习的原因-_-
  • @Menelaos 我不知道有什么具体问题,相关的源代码和很好的解释他尝试了什么以及他正在尝试做什么。这远远高于这里的平均问题:-)
  • @Esailija 没错,当你这样说的时候。可能只有标题太笼统了。

标签: java if-statement while-loop


【解决方案1】:

你更新 beerNum 然后打印出来。放部分

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

在更新 beerNum 值的那一行之后。对“bottle”和“bottles”使用单独的变量也是一个好主意。

【讨论】:

  • 花了我应该的时间,但我现在明白了!谢谢大家!
【解决方案2】:

您也可以不使用循环并使用递归来做同样的事情。

public class Bottles {
    public static void main(String[] args) {
        removeBottle(100);
    }

    private static void removeBottle(int numOfBottles) {
        // IF the number of bottles is LESS THAN OR EQUAL to 1 print singular version
        // ELSE print plural version
        if (numOfBottles <= 1) {
            System.out.println(numOfBottles + " bottle of beer on the wall.");
        } else {
            System.out.println(numOfBottles + " bottles of beer on the wall.");
        }

        // print of the rest of song
        System.out.println("Take one down.");
        System.out.println("Pass it around.\n"); // "\n" just puts new line

        numOfBottles--; // remove a bottle

        // IF the number of bottles is GREATER THAN OR EQUAL to 1 do it again!
        // ELSE no more bottles =(
        if (numOfBottles >= 1) {
            removeBottle(numOfBottles);
        } else {
            System.out.println("No more bottles of beer on the wall!");
        }
    }
}

【讨论】:

  • 不过,这是一种让堆栈溢出的好方法。在这种特殊情况下,我个人也发现循环更具可读性。
  • 啊,这完全是一种不同的方法,我已经解决了,但还是谢谢!
  • @LearnIT,记住这一点很好,以后会派上用场。
  • @RaptorDotCpp,如果你没有正确终止它只会导致堆栈溢出。它基本上就像一个while循环。我同意循环更容易阅读,但我认为在某些情况下递归更快。
  • 或者如果你的堆栈变得太大。当然,这不会发生在这里。不在任何现代机器上。
猜你喜欢
  • 1970-01-01
  • 2015-10-23
  • 2023-03-22
  • 2012-01-06
  • 2012-06-18
  • 2012-01-17
  • 2018-06-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多