我是编程新手。我试图使用递归和 if-else 语句仅打印 99 瓶啤酒的歌词。这是我的代码。我怎样才能更好地打印歌词。
方法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);
}
最佳答案
您可以将两个 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);
关于java - 递归和 if-else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44227959/