Recursion 为什么methodExit也执行多次-请解释此代码的流程
运行此代码后,method1将执行11次,这是可以理解的,但methodExit为什么会运行10次,根据我的说法,method1应该运行10次,但在返回后,它应该转到methodExit并只运行一次。请解释一下 代码:Recursion 为什么methodExit也执行多次-请解释此代码的流程,recursion,Recursion,运行此代码后,method1将执行11次,这是可以理解的,但methodExit为什么会运行10次,根据我的说法,method1应该运行10次,但在返回后,它应该转到methodExit并只运行一次。请解释一下 代码: public class demo { static int temp=0; static void methodExit() { System.out.println(" method exit executed "+temp);
public class demo {
static int temp=0;
static void methodExit() {
System.out.println(" method exit executed "+temp);
temp++;
}
static void method1()
{
System.out.print(" "+temp);
temp++;
if(temp==11)
{
temp=0;
return;
}
method1();
methodExit();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
method1();
}
}
输出:
0 1 2 3 4 5 6 7 8 9 10
method exit executed 0
method exit executed 1
method exit executed 2
method exit executed 3
method exit executed 4
method exit executed 5
method exit executed 6
method exit executed 7
method exit executed 8
method exit executed 9
那是Java吗?如果
temp==11
那么method1不调用methodExit,那么也应该标记语言。所有其他时间对method1的每次调用都会导致对methodExit的调用。如果是这种情况,那么为什么method1首先执行到最后,然后methodExit开始@ThiloBecausemethodExit()
在method1()
之后调用。因此method1
在调用methodExit()
之前完成(包括对更多method1
的所有递归调用)。我建议您在一张纸上可视化调用序列,或在调试器中逐步执行。