好的,这一定是非常愚蠢的事情。...我的陈述返回2:


当我打印出值时,它们都是正确的
return语句以某种方式是错误的


码:

public static void main (String [] args)
{
    System.out.println(countToTen(1));
}

public static int countToTen(int last_answer){
    last_answer++;
    if(last_answer != 10){
        countToTen(last_answer);
    }
    return  last_answer;
}

最佳答案

尝试将您的if语句替换为:

if(last_answer != 10){
    return countToTen(last_answer);
}


没有return语句,将执行递归调用,但永远不会返回计算结果。

带有损坏代码的调用顺序如下:

countToTen(1)
 -> countToTen(2)
 -->  countToTen(3)
 ---> more calls to countToTen()
 --- ... --> countToTen(10) // do nothing, and return to the top-level method call
 -> return 2 // 2 because you incremented it using lastAnswer++

09-25 18:36