简体   繁体   English

递归和if-else语句

[英]Recursion and if-else statement

I am new to programming. 我是编程新手。 I am trying to use recursion and if-else statement only to print the 99 beers lyrics. 我正在尝试使用递归和if-else语句仅打印99啤酒的歌词。 Here is my code. 这是我的代码。 How can I make it better to print the lyrics well. 如何更好地打印歌词。

The method countdown prints the lyrics while countdownB should print the number from number 99 all the way to zero. 方法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);
}

You can merge the two countdown methods into one method. 您可以将两个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);
    }
}

You should call this when you want to print 99 lyrics. 要打印99首歌词时,应调用此选项。

countdown(99);

In general recursion is used to solve problems by focussing on base cases and on how a general case can be simplified towards a base case. 通常,递归用于解决问题,方法是将重点放在基本案例上,并关注如何将通用案例简化为基本案例。

To use recursion to print the 99 bottles of beer on the wall one should identify the base cases. 要使用递归在墙上印刷99瓶啤酒,应确定基本情况。 To me those would be for 1 bottle of beer, because then the lyrics end with no more bottles of beer on the wall . 对我来说,那将是一瓶啤酒,因为歌词结束时墙上不再有瓶啤酒

To simplify things I am going to disregard pluralization. 为简化起见,我将不考虑多元性。 Then the general case is the standard lyrics. 那么一般情况就是标准歌词。 To implement this solutions pseudo-code could look like this. 要实现此解决方案,伪代码应如下所示。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM