2016-06-08 28 views
-1

链接的问题:http://rosettacode.org/wiki/99_Bottles_of_Beer刚刚启动的Java,这是一个适合99瓶瓶装啤酒的适当解决方案吗?

我的代码:

import java.util.Scanner; 

public class Application { 
public static void main(String[] args) { 

    Scanner input = new Scanner(System.in); 

    System.out.println("Please enter the number of bottles of beer on the wall: "); 

    int X = input.nextInt(); 

    do { 
     if (X == 1) { 
      System.out.println(X + " bottle of beer on the wall"); 
      System.out.println(X + " bottle of beer"); 
      System.out.println("Take one down, pass it around"); 
      System.out.println(X-- + " bottle of beer on the wall"); 
      System.out.println(); 
     } else { 
      System.out.println(X + " bottles of beer on the wall"); 
      System.out.println(X + " bottles of beer"); 
      System.out.println("Take one down, pass it around"); 
      System.out.println(X-- + " bottles of beer on the wall"); 
      System.out.println(); 
     } 
    } while (X >= 0); 
} 

}

是否有这样做的更好的方法?在学校递归方面我已经感受到了一点点,但不知道如何在Java中实现它。有什么建议么?

+0

那么你可以避免难以发现的副作用......''System.out.println(X-- +“瓶壁上的啤酒”);' –

+0

我投票结束这个问题作为题外话,因为它属于http://codereview.stackexchange.com/ –

回答

0

既然你知道瓶子的数量,我会用for循环来代替do。由于输入的瓶子数量可能是1,我会用一段时间而不是do/while(如果您希望至少发生一次,请使用do/while)。

在风格上,X应该是x或更好,numberOfBottles。

我还动:

System.out.println(); 

在对的if/else,因为它是上是相同的。

最后,我还会将X--自动移动到一行,以便人们不必考虑在打印之前或之后发生的X--

+0

是否有任何具体的原因,为什么你建议一个循环的do/while循环?是因为效率吗?我不太确定你的意思是“至少发生一次”,你能重申吗? –

+0

通常:当你知道迭代次数时,使用for循环;当你想让它发生0次或更多次时使用while循环;当你想让它发生1次或更多次时使用do/while。 – TofuBeer

+0

如果我想让句子在语法上正确,我将如何编写for循环sysout代码? –

0

这是一个非常容易植入for循环。注:我用“\ n”,这是你打印到控制台后,你如何做一个新的生产线,如果你不熟悉

public static void main(String[] args) { 

    Scanner input = new Scanner(System.in); 

    System.out.println("Please enter the number of bottles of beer on the wall: "); 

    int numOfBottles = input.nextInt(); 

    for(int i = numOfBottles; i >= 1; i--){ 
     System.out.println(i + " bottle of beer on the wall"); 
     System.out.println(i + " bottle of beer"); 
     System.out.println("Take one down, pass it around"); 
     System.out.println(i-1 + " bottle of beer on the wall\n"); 

} 
0

试试这个do-while循环: -

do { 
     System.out.println(X + " bottles of beer on the wall"); 
     System.out.println(X + " bottles of beer"); 
     System.out.println("Take one down, pass it around"); 
     X--; 
     System.out.println(X + " bottles of beer on the wall\n"); 
    } while (X > 0); 
相关问题