0

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);
}
4
  • 2
    Can you post the desired output ? Commented May 28, 2017 at 13:43
  • I want to find a way to print the output in method countdownB to be the first part of the output on method countdown Commented May 28, 2017 at 13:48
  • Post it in the question. Commented May 28, 2017 at 13:55
  • In addition to describing the difference between the current output and the deisred output, please rubber duck your code. Explain (to your self) which line does what when. If you manage to explain it to yourself, then edit yoru question and describe it to us. Commented May 28, 2017 at 14:18

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.