回顾我的笔记,并想知道如果任何人有什么下面发生的简要说明:基本递归与如果else语句(JAVA)
public class HelloWorld{
public static void main(String[]args){
helloWorld(10);
}
public static void helloWorld(int n){
if(n > 0){
System.out.println("HelloWorld! " + n);
helloWorld(n-1);
}
System.out.println("GoodBye from " + n);
}
}
输出:
HelloWorld! 10
HelloWorld! 9
HelloWorld! 8
HelloWorld! 7
HelloWorld! 6
HelloWorld! 5
HelloWorld! 4
HelloWorld! 3
HelloWorld! 2
HelloWorld! 1
GoodBye from 0
GoodBye from 1
GoodBye from 2
GoodBye from 3
GoodBye from 4
GoodBye from 5
GoodBye from 6
GoodBye from 7
GoodBye from 8
GoodBye from 9
GoodBye from 10
只是要清楚,我完全理解了递归和调用堆栈展开的情况。我的问题是关于什么发生在我包括下面的else语句:
public static void helloWorld(int n){
if(n > 0){
System.out.println("HelloWorld! " + n);
helloWorld(n-1);
}else{
System.out.println("GoodBye from " + n);
}
}
输出:
HelloWorld! 10
HelloWorld! 9
HelloWorld! 8
HelloWorld! 7
HelloWorld! 6
HelloWorld! 5
HelloWorld! 4
HelloWorld! 3
HelloWorld! 2
HelloWorld! 1
GoodBye from 0
为什么调用堆栈出现,当它击中else语句不放松?
为什么只有当n为0(或更小)时才会打印再见1-10? – Dukeling
当它进入'if'语句时,你为什么期望它执行else语句呢? –
0只能达到一次,因此只有一次执行else分支。在两个版本中堆栈解绕发生了11次,只有没有'else'添加了10个额外的打印。 –