java - 在 Java 中使用递归时如何解决 StackOverflowError?

标签 java recursion text-files stack-overflow outputstream

我目前正在编写一个程序,该程序将计算汉诺塔问题中所需采取的 Action 。我需要将所有 Action 写入输出 .txt 文件。

当我尝试执行此操作时,我会在 towerOfHanoiMoves 方法中的 if 语句开头保留一次 StackOverFlow 错误,并在第一次递归调用同一方法时多次保留 StackOverFlow 错误。

我猜测错误与 outStream 以及每次将其传递给方法有关,但我不确定。如果是这种情况,我无法弄清楚如何写入用户在 main 方法中给出的相同输出文件。

此外,代码将始终打印 try catch block 中的“finally”语句以及 if 语句中的 outStream 语句中的信息,但不会打印其他内容。

我尝试在 towerOfHanoiMoves 方法中使用 outStream.write 命令后刷新 outStream,但这根本没有帮助。

此外,我还导入了 BufferedReader、FileReader 等的所有库,但它们不会在我的问题中正确显示。所以它们出现在代码中只是为了让您知道,但它们只是没有出现在此处的代码中。

public class TowerofHanoiRecursive {

    public static void main(String[]args)throws IOException,
    EmptyFile,
    FileNotFoundException {
        int n; //number of disks in tower
        String rodLeft = "A",
        rodRight = "C",
        rodMiddle = "B";
        FileReader inputStream = null;
        FileWriter outputStream = null;
        BufferedReader str = null;

        try {
            outputStream = new FileWriter(args[1]); // output file
            inputStream = new FileReader(args[0]); // input file
            str = new BufferedReader(inputStream);
            String nextLine;
            File newFile = new File(args[0]);

            if (newFile.length() == 0) { //Tests if input file is empty
                throw new EmptyFile("Input file is empty.");

            }
            while ((nextLine = str.readLine()) != null) {
                outputStream.write("----------------------------------------"
                     + "------------------------\n");
                outputStream.write("Number of Disks in Starting Tower = "
                     + nextLine);
                n = Integer.parseInt(nextLine);

                towerOfHanoiMoves(n, rodLeft, rodRight, rodMiddle,
                    outputStream);

            }

        } catch (FileNotFoundException e) {
            outputStream.write("Input file not found.");
            outputStream.flush();
            if (outputStream != null)
                outputStream.close();

        }
        catch (EmptyFile e) {
            outputStream.write(e.getMessage());
            outputStream.flush();
            if (inputStream != null)
                inputStream.close();
            if (outputStream != null)
                outputStream.close();
            str.close();

        }
        finally {
            outputStream.write("");
            outputStream.write("Total time to taken to solve Tower: ");
            outputStream.write("\n\nSuccess!");
            outputStream.flush();

            if (inputStream != null)
                inputStream.close();
            if (outputStream != null)
                outputStream.close();
            str.close();
        }

    }

    public static void towerOfHanoiMoves(int n, String srcRod, String destRod,
        String spareRod, FileWriter outStream) {
        try {
            if (n == 1) {
                outStream.write("\nMove disk 1 from rod " + srcRod + " to rod "
                     + destRod + ".");
            }
            towerOfHanoiMoves(n - 1, srcRod, spareRod, destRod, outStream);
            outStream.write("\nMove disk " + n + " from rod " + srcRod
                 + " to rod " + destRod + ".");
            towerOfHanoiMoves(n - 1, spareRod, destRod, srcRod, outStream);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

最佳答案

if (n == 1) {
    outStream.write("\nMove disk 1 from rod " + srcRod + " to rod + destRod + ".");
} else {
   ...
}

或添加另一个中断条件

基本上你会用 n 得到负值

PS 拥有调试器可以帮助您逐步完成代码并检查变量 或者只是每一步的 System.out.println 变量

关于java - 在 Java 中使用递归时如何解决 StackOverflowError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55387592/

相关文章:

java - 从内容 URI 获取目录路径

c++ - 故障跟踪递归函数

php - 类别和子类别的递归函数

java - 将 .txt 文件传输到数组时出错(线程异常)

c# - 将文本文件中的每一行放入数组 C#

Java Rest Service POST 对 InnerClasses 属性存在分歧

java - 实现复杂首选项屏幕的最佳方式?

java - 如何将 OnClickListener 设置为 Expandable RecycleView

Python - 了解传递给递归函数的变量的范围

ios - 创建、保存和读取文本文件