为什么Java里会执行递归后面的语句
巴扎黑
巴扎黑 2017-04-17 17:47:43
0
8
390

代码为:

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");
}

执行效果为

为什么递归后会执行后面的输出语句,而且是在最后一次一起执行,不是每次递归前输出

巴扎黑
巴扎黑

reply all(8)
大家讲道理

Obviously, your logic should not be recursivescore,而是在mainin 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.

Peter_Zhu

Think about the last execution first, and then push forward

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template