您现在的位置是:首页 > 编程开发 > Java > Java

试着学习JAVA,我想写99瓶啤酒歌

编辑:站长来源:网络整理作者: 未知2020-12-15Java

简介我是JAVA编程的新手,之前只用 Python编程. 我正在试图找出为什么当我执行我的代码时,我会在墙上找到一堆重复的“啤酒瓶#”. package BeerBottle; public class BeerBot { public static void main (String [] args){ int beerNum = 99; String word = "bottl

我是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

谢谢您的帮助

解决方法

循环的最后一行打印行与下一循环的第一行打印行相同,所以这不是问题.要在视觉上分隔每个循环的输出,请在方法的最后打印一个空行.然后你会看到这样的事情:

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

很赞哦! ()

点击排行

本栏推荐

猜你喜欢