【问题标题】:Reading a .txt file that results in a stackoverflow error读取导致 stackoverflow 错误的 .txt 文件
【发布时间】:2015-04-12 01:35:29
【问题描述】:

谁能帮我确定我的代码做错了什么。我收到堆栈溢出错误。在我的代码结束时,我使用递归并且我没有停止程序的基本情况。它会一直循环并显示我的文本文件,直到我收到 stackoverflow 错误。

public class Reader
   {
        public static String readFinalQuestionBank() throws Exception
        {   
            File textFile = new File("C:\\Users\\Joseph\\Documents\\School Files - NHCC\\CSci 2002\\FinalQuestionBank_JosephKraemer.txt");  //file location

            try
            {
                Scanner scan = new Scanner(textFile);                   //Scanner to import file

                while(scan.hasNextLine())                               //Iterator - while file has next line
                {
                    String qBank = scan.nextLine();                     //Iterator next line
                    String[] tempArray = qBank.split("::");             //split data via double colon

                    System.out.println(qBank);           //print data line
                }
                scan.close();                  //close scanner

            }
            catch(FileNotFoundException e)
            {
                 e.printStackTrace();
            }       
            return readFinalQuestionBank();         //use of Recursion
        }//end method readFinalQuestionBank
    }//end class Reader 

【问题讨论】:

  • 除了一遍又一遍地读取文件直到堆栈溢出之外,您希望递归完成什么?
  • 您似乎已经发现了问题所在。你还想知道什么?
  • 请指定您要使用代码完成的任务。就目前而言,代码与在 while(true) 块中调用非递归 readFinalQuestionBank() 相同,不同之处在于您永无止境的递归调用最终会耗尽正在运行的线程的所有堆栈缓冲区并导致异常.

标签: java recursion split java.util.scanner


【解决方案1】:

如果您的主要目标是通过实现递归来读取整个输入文件,请查看以下示例,它将while 语句替换为递归方法调用。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Reader
{
     public static String readFinalQuestionBank() throws Exception
     {   
         File textFile = new File("C:\\Users\\Diego\\Documents\\sandbox\\input.txt");
         String output = "";
         try
         {
             Scanner scan = new Scanner(textFile);                   
             output = readLineRecursively(scan);
             scan.close();                  
         }
         catch(FileNotFoundException e)
         {
              e.printStackTrace();
         }       
         return output;         
     }

    private static String readLineRecursively(Scanner scan){
        if(!scan.hasNextLine()){
            return "";
        }
        String qBank = scan.nextLine();                     
        return qBank + "\n" + readLineRecursively(scan);
    }

    public static void main(String[] args){
        try {
            System.out.println(readFinalQuestionBank());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-14
    • 2015-09-12
    • 1970-01-01
    相关资源
    最近更新 更多