我正在尝试将歌词打印到99瓶啤酒中,但是,我得到了无限的递归,在第一节开始。关于如何摆脱这种无限递归的任何想法?
public static void bottlesOfBeer(int beer) { //prints the lyrics for "99 bottles of Beer on the wall".
if (beer == 99) {
for (beer = 99; beer > 0; bottlesOfBeer(beer - 1)) {
System.out.println(beer
+ " bottles of Beer on the wall!"
+ beer + " bottles of Beer!"
+ " Take one down, pass it around, "
+ minusOneBeer(beer) + " bottles of beer on the wall!");
}
}
}
public static int minusOneBeer(int beer) {
return beer - 1;
}
}
答案 0 :(得分:2)
你的问题并不是递归方法。递归通常会执行而不是循环。你有一个奇怪的递归和迭代混搭。
如果你的要求是通过递归来解决问题,那么找出如何在没有任何循环结构的情况下做到这一点(不,我不会为你做功课)。实际上你已经拥有了大部分已经存在的东西。
答案 1 :(得分:1)
我认为这不符合你的想法。有递归但它只有一层深。当你调用bottlesOfBeer(beer - 1)
时,由于方法开头的if (beer == 99)
,这个递归调用保证不会做任何事情。
如果if
,您只会输入beer == 99
语句,因此当您使用beer - 1
再次调用该方法时,它将失败if语句并结束递归。
您所看到的是一个无限循环(不同于无限递归),因为for
循环中没有beer
递减的本地副本。因此,beer
循环中的for
将始终为99,因此for循环将永远运行。
你可能想要这样的东西:
public static void bottlesOfBeer(int beer) {
if (beer > 1) {
System.out.println(beer
+ " bottles of Beer on the wall!"
+ beer + " bottles of Beer!"
+ " Take one down, pass it around, "
+ (beer - 1) + " bottles of beer on the wall!");
bottlesOfBeer(beer - 1);
}
else if (beer == 1) {
System.out.println(beer
+ " bottle of Beer on the wall!"
+ beer + " bottle of Beer!"
+ " Take one down, pass it around, "
+ " no more bottles of beer on the wall!");
}
else {
// Do nothing if beer <= 0
}
}
答案 2 :(得分:0)
查看您的bottlesOfBeer(int beer)
方法 -
public static void bottlesOfBeer(int beer)
它的返回类型是无效的。您可以在for循环中将其用作增量/减量的占位符
从public static void bottlesOfBeer(int beer)
这个方法返回一些int。
希望它会有所帮助 感谢。
答案 3 :(得分:0)
好的,问题是你从未真正减少啤酒。正确的方法是用bottlesOfBeer(beer-1)
替换beer--
部分。每次循环运行时,这将自动减少啤酒。
这也意味着可以删除if(啤酒== 99)支票。如果您始终希望它从99开始,请创建一个名为BEERS_START = 99
的常量并使用它来初始化啤酒。如果您希望它能够从任意整数开始,那么只需删除检查。
编辑: 鉴于您的老师要求递归,您应该以不同的方式处理递归。我不会提供代码,因为我无法提供一个很好的例子,而基本上没有为你编写任务。但是,有一种比你正在做的更简单的方法。在这种方法中根本不需要for循环。就此而言,您也不需要if语句。尝试在没有for循环的情况下设计递归,并且不使用if语句。一旦到达那里,最终结果将变得更加简单。
如果您在尝试之后仍然遇到问题,请在问题中发布一些更新的代码,其中包含您的新尝试,并在另一条评论中告诉我。我会看看我是否能从那里得到帮助。
答案 4 :(得分:0)
试试这个
public class HelloWorld {
public static void main(String[] args) {
beers(3);
}
public static void beers(int n) {
if (n == 0){
System.out.println();
System.out.println("No bottles of beer on the wall");
System.out.println("no bottles of beer,");
System.out.println("ya’ can’t take one down, ya’ can’t pass it around,");
System.out.println("’cause there are no more bottles of beer on the wall!");
}
else{
System.out.println(n + " bottles of beer on the wall");
System.out.println(n + " bottles of beer");
System.out.println("Ya drink one down, pass it around,");
System.out.println((n-1) + " bottles of beer on the wall");
System.out.println();
beers(n - 1);
}
}
}