Leslie
Leslie

Reputation: 51

Stack overflow error when reading from a file

When I try to test the file reading, I get a stack overflow error. I know why this occurs, but i don't know why it's happening in my program and how to fix it. Here's my main, load method, display method, and file:

public static void main(String[] args) 
{
    try 
    {
        loadEmployeesFromFile("employees.txt");
        displayEmployees();    
    }catch (FileNotFoundException e) 
    {
        System.err.println("File error: " + e.getMessage());
    }catch (IOException e) 
    {
        System.err.println("IO error: " + e.getMessage());
    }
}

private static void loadEmployeesFromFile(String filename) throws IOException {
    try (Scanner fin = new Scanner(new File(filename));) 
    {
        String employeeRecord;
        String fields[];

        while (fin.hasNext()) 
        {
            employeeRecord = fin.nextLine();
            fields = employeeRecord.split(",");

            switch (fields[0]) {
                case "F":
                    staff[numberOfRecords] = new FullTime(Double.parseDouble(fields[1]), fields[2], fields[3]);
                    break;
                case "P":
                    staff[numberOfRecords] = new PartTime(Double.parseDouble(fields[2]), Double.parseDouble(fields[3]), fields[4], fields[5]);
                    break;    
                case "I":
                    staff[numberOfRecords] = new Intern(fields[1], fields[2]);
                    break;
            }
            numberOfRecords++;
        }// end while
    }
}

private static void displayEmployees() 
{
    for (int i = 0; i <= numberOfRecords - 1; i++) 
    {
        System.out.println(staff[i]);
    }
}

I,i1First,i1Last

F,65000.0,ft1First,ft1Last

P,13.5,50.0,pt1First,pt1Last

F,55000.0,ft2First,ft2Last

P,20.0,40.0,pt2First,pt2Last

Upvotes: 0

Views: 218

Answers (1)

Vihar
Vihar

Reputation: 3831

You have checked for while(fin.hasNext()) but haven't performed fin.next() so the iterator never goes forward try doing

while(fin.hasNext()){
      ...
      ...
      fin.next();
}

hope this helps!

Good luck!

Upvotes: 1

Related Questions