递归程序有一个带有示例方法的StackOverflowError [重复]

问题描述 投票:-1回答:2

这个问题在这里已有答案:

我创建了一个递归程序来打印消息Hello几次,但在编译中失败了StackOverflowError。

package com.recre;

public class Recursionhello {
    static void p() {
        System.out.println("Hello");
    p();
}

public static void main(String[] args) {
    p();
    }
}

它多次打印输出“Hello”,然后打印以下错误消息。

出来 -

Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Exception in thread "main" java.lang.StackOverflowError
 at java.io.FileOutputStream.write(Unknown Source)
 at java.io.BufferedOutputStream.flushBuffer(Unknown Source)
 at java.io.BufferedOutputStream.flush(Unknown Source)
 at java.io.PrintStream.write(Unknown Source)
 at sun.nio.cs.StreamEncoder.writeBytes(Unknown Source)
 at sun.nio.cs.StreamEncoder.implFlushBuffer(Unknown Source)
 at sun.nio.cs.StreamEncoder.flushBuffer(Unknown Source)
 at java.io.OutputStreamWriter.flushBuffer(Unknown Source)
 at java.io.PrintStream.write(Unknown Source)
 at java.io.PrintStream.print(Unknown Source)
 at java.io.PrintStream.println(Unknown Source)
 at com.recre.Recursionhello.p(Recursionhello.java:5)
 at com.recre.Recursionhello.p(Recursionhello.java:6)
 at com.recre.Recursionhello.p(Recursionhello.java:6)
 at com.recre.Recursionhello.p(Recursionhello.java:6)
 at com.recre.Recursionhello.p(Recursionhello.java:6)
 at com.recre.Recursionhello.p(Recursionhello.java:6)
 at com.recre.Recursionhello.p(Recursionhello.java:6)
 at com.recre.Recursionhello.p(Recursionhello.java:

在这里,我需要关于错误的助手和关于递归的一些解释。

java recursion error-handling stack-overflow
2个回答
1
投票

基本上,递归是一种方法调用自身产生循环的方式。任何循环都需要终止条件。在这种情况下,您将错过此循环终止的条件。关于堆栈溢出错误,当您调用方法时,它会被加载到堆栈上,堆栈限制为256 KB。每个方法调用都会占用堆栈上的一些内存,当堆栈的大小被填满时,我们再次尝试通过调用自身加载另一个方法来获取StackOverflowError。


0
投票

Java中的任何递归程序都必须具有退出条件,如下所示:

public class Recursionhello {
    static void p(int times) {
        System.out.println("Hello");
        if(times > 0) {
            p(times - 1);
        }
    }

    public static void main(String[] args) {
        p(5);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.