递归函数导致StackOverflowError

时间:2014-11-30 21:04:39

标签: java recursion

我不明白为什么这个函数会导致堆栈溢出错误。如果有人能向我解释,我真的很感激它!

public static int count7(int n){
    if(n == 0){
        return 0;
    }
    if (n==7){
        return 1;
    }
    if (n%10 == 7){
        return 1 + count7(n/10);
    }
    else{
        return count7(n/10);
    }
}

它适用于" 7777777"和那样的东西,但" 999999"给出错误,以及" 123"和" 47571"。

所以我补充道:

if(n == 0){
        return 0;
    }

现在似乎工作了!

3 个答案:

答案 0 :(得分:2)

在某些情况下,你有无休止的再生调用(如果n永远不等于7)。

例如:

n = 123     //initial call
n = 12    //1st recursive call
n = 1    //2nd recursive call
n = 0    //3rd recursive call

值永远不是n = 7,因此你永远不会返回任何东西,并且你一直在调用count7(n / 10)

您应该更改代码以捕获所有基本情况:

public static int count7(int n){
if (n==7){
    return 1;
} else if (n < 7) {
    return 0; // I assumed you wanted to return 0, you can change this to return 1...
}
if (n%10 == 7){
    return 1 + count7(n/10);
}
else{
    return count7(n/10);
}
}

答案 1 :(得分:0)

你没有停止状态。你应该添加:

if (n == 0) return 0;

答案 2 :(得分:0)

好吧,当最后一个数字没有特别满足这两个条件时,它只是调用else块

return count7(n/10)

由于将单个数字整数除以10,因此将其截断为0,因此与调用此行的条件不匹配,直到发生溢出。您可以添加一个基本声明,说明

if(n==0) return 0;

另外,为了帮助调试过程,我建议您使用print语句跟踪您的过程,以查看变量发生了什么。例如,添加

System.out.println("n = " + n);

在每个返回语句之前。