代码为:
public static void main(String[] args) {
// TODO Auto-generated method stub
score();
}
public static void score(){
System.out.println("请输入一个5分制成绩");
Scanner in = new Scanner(System.in);
int score = in.nextInt();
if(score>=0&&score<=5){
switch(score){
case 5:System.out.println("优秀");
break;
case 4:System.out.println("良好");
break;
case 3:System.out.println("及格");
break;
default:System.out.println("不及格");
break;
}
}
else{
score();
}
System.out.println("over");
}
执行效果为
为什么递归后会执行后面的输出语句,而且是在最后一次一起执行,不是每次递归前输出
Obviously, your logic should not be recursive
score
,而是在main
in loop control.PS: Recursion is suitable for use in some logic that is obviously easy to read after use, such as the Fibonacci sequence. Recursion sometimes needs to be transformed into a loop, because when the recursion level is deep, its performance is very poor and exponentially worse.
To understand recursion, the best way is to single-step debugging, everything will be understood
Recursion, recursion, of course, executes the entire function body every time,
Because your output code is after the recursive call, it is output together last. When the innermost recursion reaches the last sentence, it returns to the outer layer, continues to execute the statement after the recursive call, that is, the output statement of the outer layer, and then returns to the outer layer until the outermost layer.
Because you entered 3 at the end, you left the if instead of the else. After the if came out, over was printed, and then every time the recursive loop came out, over was printed
Because the journey is not over yet and has to continue
Because of recursion, the magic of recursion is not only that it calls itself every time, but the most amazing thing is that after the last recursion is executed, it will return upward layer by layer, so the output over will be output at the end. Instead of outputting an over every time it is called.
Think about the last execution first, and then push forward