2014-09-05 98 views
0

我正在写一个代码来输出“99瓶啤酒在墙上”程序。我试图说“墙上有一瓶啤酒”。而不是瓶子。我不确定我的代码有什么问题。任何帮助,将不胜感激。String.replace()无法正常工作?我究竟做错了什么?

public class BeerOnTheWall { 

public static void handleCountdown() { 

    int amount = 99; 
    int newamt = amount - 1; 
    String bottles = " bottles"; 

     while(amount != 0) { 

      if(amount == 1) { 
       bottles.replace("bottles", "bottle"); 
      } 

     System.out.println(amount + bottles +" of beer on the wall, " 
       + amount + bottles +" of beer! You take one down, pass it around, " 
       + newamt + " bottles of beer on the wall!"); 
     amount--; 
     newamt--; 



    } 



    System.out.println("Whew! Done!"); 
} 

public static void main(String args[]) { 
    handleCountdown(); 
} 


} 

我有一个if语句是假设检查int“amount”是否等于1,然后用“bottle”替换“bottles”。

任何帮助?

谢谢。

回答

3

String#replace返回修改后的String,所以你需要更换:

if(amount == 1) { 
    bottles.replace("bottles", "bottle"); 
} 

有:

if(amount == 1) { 
    bottles = bottles.replace("bottles", "bottle"); 
} 

the documentation

+0

我不能相信我错过了!多么简单的错误!谢谢! – John 2014-09-05 03:29:42

+0

@John不客气:) – AntonH 2014-09-05 03:30:29

相关问题