离开递归调用时如何打印

时间:2015-03-04 03:18:55

标签: java recursion printing

离开递归通话后如何打印到屏幕。例如,当执行ackermann函数时。

acker(1,2);
public int acker(int m, int n){
    System.out.println("Entered acker");
    if(m == 0)
        return n + 1;
    if(n == 0)
        return acker(m-1,1);
    return acker(m-1, acker(m, n - 1));
}

我可以在输入acker方法时打印,但是在方法完成调用后我将如何打印。例如,输出将是:

Entered acker
Entered acker 
Entered acker 
Entered acker
//Here it would say leaving because its not making another recursive call

1 个答案:

答案 0 :(得分:1)

重构将返回值赋给变量,打印消息,然后返回值:

public int acker(int m, int n){
    System.out.println("Entered acker");
    int result;
    if(m == 0)
        result = n + 1;
    else if(n == 0)
        result = acker(m-1,1);
    else
        result = acker(m-1, acker(m, n - 1));
    System.out.println( "Returning " + result + " from acker");
    return result; 
}