[英]Recursion and if-else statement
我是编程新手。 我正在尝试使用递归和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);
通常,递归用于解决问题,方法是将重点放在基本案例上,并关注如何将通用案例简化为基本案例。
要使用递归在墙上印刷99瓶啤酒,应确定基本情况。 对我来说,那将是一瓶啤酒,因为歌词结束时墙上不再有瓶啤酒 。
为简化起见,我将不考虑多元性。 那么一般情况就是标准歌词。 要实现此解决方案,伪代码应如下所示。
public void song(int n) {
if (n == 1) {
singBaseCase();
} else {
singGeneralCase(n);
song(n - 1);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.