程序只读取文本文件的最后一行

时间:2016-11-07 00:33:13

标签: java text while-loop java.util.scanner

我试图测试我的程序,看看我的文本文档中的每一行是否都存储了。出于某种原因,只存储和打印最后一行。我试着看一个类似的问题,但是解决方案并没有奏效。有什么方法可以解决这个问题吗?

import java.io.*;
import java.util.*;

public class employeeDriver {

    public static void main(String[] args) throws IOException {

        try {
            File file = new File("tester.txt");
            Scanner readFile = new Scanner(file);
            Employee employee2014[] = new Employee[10];
            Employee employee2015[] = new Employee[10];

            int indexEmployee2014 = 0;
            int indexEmployee2015 = 0;

            while(readFile.hasNext()) {
                String year = readFile.next();
                String employeeTitle = readFile.next();
                String employeeName = readFile.next();
                double monthlySalary = readFile.nextDouble();

                if(employeeTitle.equalsIgnoreCase("Employee")) {
                    Employee employee = new Employee(employeeName, monthlySalary);
                    if(year.equals("2014")) {
                        employee2014[indexEmployee2014++] = employee;
                    }
                    if(year.equals("2015")) {
                        employee2015[indexEmployee2015++] = employee;
                    }
                }

                if(employeeTitle.equalsIgnoreCase("Salesman")) {
                    double annualSales = readFile.nextDouble();
                    Salesman salesman = new Salesman(employeeName, monthlySalary, annualSales);
                    if(year.equals("2014")) {
                        employee2014[indexEmployee2014++] = salesman;
                    }
                    if(year.equals("2015")) {
                        employee2015[indexEmployee2015++] = salesman;
                    }
                }

                if(employeeTitle.equalsIgnoreCase("Executive")) {
                    double stockPrice = readFile.nextDouble();
                    Executive executive = new Executive(employeeName, monthlySalary, stockPrice);
                    if(year.equals("2014")) {
                        employee2014[indexEmployee2014++] = executive;
                    }
                    if(year.equals("2015")) {
                        employee2015[indexEmployee2015++] = executive;
                    }
                }
            }
            for (int i = 0; i < indexEmployee2015; i++) {
                System.out.print(employee2015[i]);
            }
        } catch(FileNotFoundException e) {
            System.out.println("File not found");
            System.exit(0);
        }
    }
}

文字档案

2014 Employee Baker,John 15000
2014 Salesman Stein,Amanda 30000 1100000
2014 Executive Kettner,Jessica 53
2015 Employee Edwards,Zach 20000
2015 Salesman Douglas,Shelby 45000 2345
2015 Executive Matthews,Correy 67000 48

0 个答案:

没有答案