每次在递归语句(java)中打印返回值?

时间:2012-03-04 20:01:00

标签: java recursion

该项目是编写一个递归方法,打印参数并返回每一步 这是我到目前为止所做的:

public static int summation(int lower, int upper){
    if (lower > upper)
        return 0;
    else{
        System.out.println("Current lower bound: " + lower);
        System.out.println("Upper bound: " + upper);
        return lower + summation(lower+1, upper);
    }

它几乎是完美的,唯一缺少的就是每次打印返回。怎么做呢?

2 个答案:

答案 0 :(得分:1)

这个怎么样:

public static int summation(int lower, int upper){
    if (lower > upper) {
        System.out.println("Returning: 0");               // print before return
        return 0;
    } else{
        int result = lower + summation(lower+1, upper);

        System.out.println("Current lower bound: " + lower);
        System.out.println("Upper bound: " + upper);
        System.out.println("Returning: " + result);       // print before return
        return result;
    }
}

答案 1 :(得分:0)

public static int summation(int lower, int upper) {
    if (lower > upper) {
        return 0;
    } else {
        int returned = lower + summation(lower + 1, upper);
        System.out.println("Current lower bound: " + lower + " | " + "Upper bound: " + upper + " | " + "returned:" + returned);
        return returned;
    }
}

enter image description here