"啤酒瓶"递归Java

时间:2016-10-20 22:38:37

标签: java recursion

所以我最近刚谈到了递归的主题,这在数学上是有道理的。这项任务要求我以递归的方式在墙上打印出#99; 99瓶啤酒"歌曲。这就是我到目前为止所拥有的

public static int bottlesOfBeer(int n) {
    if (n > 1) {
        System.out.println(n + "bottles of beer on the wall, " + n + " bottles of beer.");
        System.out.println("You take one down, pass it around. " + (n-1) + "bottles of beer on the wall.");
        bottlesOfBeer(n-1);
    } else {
        return;
    }
}

错误是程序似乎无法识别正在进行的递归子结构。我想知道它为什么不认识它。我还应该注意到这是家庭作业,所以我只想在正确的方向上轻推一下。

2 个答案:

答案 0 :(得分:0)

可能接收的错误与程序没有“识别递归子结构”无关。我愿意打赌它是因为你的方法声明返回了int,但你else中捕获的终止条件没有返回任何内容。将您的bottlesOfBeer(int n)方法重新声明为public static void bottlesOfBeer(int n)

答案 1 :(得分:0)

就像其他人在评论中所说的那样,问题很可能与它是一个返回整数的方法有关,如代码所示,

    public static int bottlesOfBeer(int n)

如果我建议改变,

    public static void bottlesOfBeer(int n)

或者只是允许方法返回一个数字。

相关问题