所以我开发了一种迭代文件的方法,该文件可能在每行中包含不同的信息,然后将它们添加到通用的ArrayList中。正如您在代码中看到的,我有三个源自超类Employee的子类;每小时,薪水和佣金。我只是想知道是否有更好的方法对此进行编码?
这是我的代码:
public void loadData(File inFile) throws IOException
{
Scanner in = new Scanner (inFile);
String employeeName;
String employeeNum;
String empDepartment;
char type;
while(in.hasNext())
{
String employee = in.nextLine();
String [] employeeList = employee.split(" ");
//This if reads in an hourly employee
if(employeeList.length == 6)
{
employeeName = employeeList[0];
employeeNum = employeeList[1];
empDepartment = employeeList[2];
type = employeeList[3].charAt(0);
double hourlyPay = Double.parseDouble(employeeList[4]);
int hoursWorked = Integer.parseInt(employeeList[5]);
employees.add(new Hourly(employeeName, employeeNum, empDepartment, type, hourlyPay, hoursWorked));
}
//This if reads in a Salary employee
else if(employeeList.length == 5)
{
employeeName = employeeList[0];
employeeNum = employeeList[1];
empDepartment = employeeList[2];
type = employeeList[3].charAt(0);
double yearlySalary = Double.parseDouble(employeeList[4]);
employees.add(new Salary(employeeName, employeeNum, empDepartment, type, yearlySalary));
}
else if(employeeList.length == 9)
{
employeeName = employeeList[0];
employeeNum = employeeList[1];
empDepartment = employeeList[2];
type = employeeList[3].charAt(0);
int weeksSinceStart = Integer.parseInt(employeeList[4]);
double baseWklySalary = Double.parseDouble(employeeList[5]);
double weeklySales = Double.parseDouble(employeeList[6]);
double totalSales = Double.parseDouble(employeeList[7]);
double commissionRate = Double.parseDouble(employeeList[8]);
employees.add(new Commission(employeeName, employeeNum, empDepartment, type, weeksSinceStart, baseWklySalary, weeklySales, totalSales, commissionRate));
}
}
in.close();
}