使用递归我如何更新本地变量

use*_*207 0 java int recursion

使用递归如何更新局部变量直到满足条件.我在下面有一个实例解释了为什么问题很好.count变量是一个局部变量,并且方法经过计数的时间设置为0.我不能将方法移动到方法之外它必须是局部变量而不是静态或其他任何东西..所需的输出应该是(3 6) )

public static int returnInt(int b) {

        int count = 0;

        if (b == 6) {

            System.out.println(count + " " + b);
        }

        b += 2;
        count++;

        return returnInt(b);

    }
Run Code Online (Sandbox Code Playgroud)

Mat*_*ick 5

通过count作为附加参数的方法:

public static int returnInt(int b, int count) {

    ... do some stuff to b, print something, check whether end-condition has been met ...

    return returnInt(b, count + 1);
}
Run Code Online (Sandbox Code Playgroud)

然后,returnInt使用额外的参数调用0以启动它.

  • ...并添加提供终止条件的逻辑.:-) (2认同)