我试图在不使用Java循环的情况下打印1到10之间的数字。在第6行中将n + 1传递给recursivefun方法调用时,它可以正常工作。但是当传递n ++时,代码将引发错误:/

public class PrintWithoutUsingLoops {

    public static void recursivefun(int n) {
        if (n <= 10) {
            System.out.println(n);
            recursivefun(n++);//an exception is thrown at this line.
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        recursivefun(1);
    }

}

最佳答案

recursivefun(n++);


n的原始值传递给递归调用(因为您使用的是后递增运算符),使此递归变为无限(因为每个递归调用都获得相同的n值,永远不会达到11),并导致StackOverflowError

更改为

recursivefun(n+1);


要么

recursivefun(++n);

关于java - 我的代码在使用递归函数时给出了异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45006374/

10-09 05:04