读取导致stackoverflow错误的.txt文件

时间:2015-04-12 01:35:29

标签: java recursion split java.util.scanner

有人可以帮我确定我的代码错误。我收到stackoverflow错误。在我的代码结束时,我正在使用递归,并且我没有基本案例来停止程序。它不断循环并显示我的文本文件,直到出现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 

1 个答案:

答案 0 :(得分:0)

如果你的主要目标是通过实现递归来读取整个输入文件,请看下面的例子,它用递归方法调用替换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();
        }
    }

}