简体   繁体   中英

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. 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.

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.

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.

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. 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);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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