2013-04-10 35 views
0
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瓶啤酒,墙上有一瓶啤酒。Java while and if

我不知道该怎么改变来解决这个问题。我是否在创建另一个部分?

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

谢谢!

+0

要去尝试这个现在 – LearnIT 2013-04-10 22:10:21

+2

这个问题表明缺乏基本的Java知识... – 2013-04-10 22:11:34

+2

这就是为什么我在学习-_- – LearnIT 2013-04-10 22:21:04

回答

4

您更新beerNum然后打印出来。把该部分

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

之后你更新beerNum的值。使用“瓶子”和“瓶子”分开的变量也是一个好主意。

+0

花了我多一点,然后它应该,但我现在得到它!多谢你们! – LearnIT 2013-04-10 22:29:21

0

你也可以做同样的没有循环,并使用递归。

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!"); 
     } 
    } 
} 
+0

虽然这是获得堆栈溢出的好方法。我个人发现循环更具可读性,在这种情况下。 – RaptorDotCpp 2013-04-10 22:33:51

+0

啊,这是一个不同的方法,我已经解决了它,但无论如何,谢谢! – LearnIT 2013-04-10 22:34:03

+0

@LearnIT,它记住它的好处,稍后会派上用场。 – 2013-04-10 22:36:19