2017-05-28 152 views
0

我是编程新手。我正尝试使用递归和if-else语句来打印99个啤酒歌词。这是我的代码。如何更好地打印歌词。递归和if-else语句

方法countdown打印歌词,而 countdownB应打印从99号一直到零的数字。

public static void countdown(int n) { 
    if (n== 0) { 
     System.out.println("no beers"); 
    } else { 
     System.out.println("more beers"); 
     countdown(n-1); 
    } 
} 

public static void countdownB(int x) { 
    if (x==0){ 
     System.out.print(""); 
    } else { 
     System.out.print(x); 
     countdownB(x-1); 
    } 
} 

public static void main(String[] args) { 
    countdownB(3); 
    countdown(3); 
} 
+2

您可以发布所需的输出吗? –

+0

我想找到一种方法来打印方法countdownB中的输出,作为方法倒计时输出的第一部分 –

+0

将其发布在问题中。 –

回答

0

一般来说递归用于通过关注基例和关于如何一般情况下可以朝向基本情况被简化来解决问题。

要使用递归方法在墙上打印99瓶啤酒,应该标识基础案例。对我来说,这些将是1瓶啤酒,因为那么歌词以结束,墙上没有更多的啤酒瓶

为了简化事情,我将无视复数化。那么一般情况下是标准歌词。为了实现这个解决方案,伪代码可能看起来像这样。

public void song(int n) { 
    if (n == 1) { 
    singBaseCase(); 
    } else { 
    singGeneralCase(n); 
    song(n - 1); 
    } 
} 
2

您可以在两个countdown方法合并为一个方法。

public static void countdown(int x) { 
    if (x == 0) { 
     System.out.println("no beers"); 
    } else { 
     // Print the number first and then the lyric 
     System.out.println(x + " more beers"); 
     countdown(x-1); 
    } 
} 

当您要打印99首歌词时,应该调用它。

countdown(99);