【发布时间】:2013-11-20 04:29:15
【问题描述】:
我正在尝试通读文件并以不同的格式创建一些对象/打印信息。
我的大部分内容都是正确的,但是由于某种原因,当它循环时,每次完成一个 if 语句时,我都会得到“字符串索引超出范围:0”(它会在它发生之前打印第一个对象)。
我已经对这个问题进行了一些研究,我认为这是因为下一行再次在位置 0 处寻找一个字符 (ID.charAt(0))。但是,我有另一个以这种方式完成的程序,它运行良好。你们有没有机会看看它并告诉我我可能在哪里搞砸了?
感谢您的帮助。我以前在这里问过几个问题,你总是帮我学习!
代码
import java.io.File;
import java.util.Scanner;
public class PayrollSystemTest2 {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Scanner input;
input = new Scanner(new File("EmployeePayrollInfo.txt"));
Employee[] Emp = new Employee[20];
while(input.hasNext())
{
String ID = input.nextLine();
if (ID.charAt(0) == 'S')
{
String first = input.nextLine();
String last = input.nextLine();
String ssn = input.nextLine();
Date DayOfBirth = new Date(input.nextInt(),input.nextInt(),input.nextInt());
double salary = input.nextDouble();
Emp[0] = new SalariedEmployee(first, last, ssn, DayOfBirth, ID, salary);
System.out.println(Emp[0].toString());
}
else if (ID.charAt(0) == 'H')
{
String first = input.nextLine();
String last = input.nextLine();
String ssn = input.nextLine();
Date DayOfBirth = new Date(input.nextInt(),input.nextInt(),input.nextInt());
double hourlyWage = input.nextDouble();
double hoursWorked = input.nextDouble();
Emp[1] = new HourlyEmployee(first,last,ssn,DayOfBirth,ID,hourlyWage,hoursWorked);
System.out.println(Emp[1].toString());
}
else if (ID.charAt(0) == 'C')
{
String first = input.nextLine();
String last = input.nextLine();
String ssn = input.nextLine();
Date DayOfBirth = new Date(input.nextInt(),input.nextInt(),input.nextInt());
Double sales = input.nextDouble();
Double rate = input.nextDouble();
Emp[2] = new CommissionEmployee(first,last,ssn,DayOfBirth,ID,sales,rate);
System.out.println(Emp[2].toString());
}
else if (ID.charAt(0) == 'B')
{
String first = input.nextLine();
String last = input.nextLine();
String ssn = input.nextLine();
Date DayOfBirth = new Date(input.nextInt(),input.nextInt(),input.nextInt());
Double sales = input.nextDouble();
Double rate = input.nextDouble();
Double salary = input.nextDouble();
Emp[3] = new BasePlusCommissionEmployee(first,last,ssn,DayOfBirth,ID,sales,rate,salary);
System.out.println(Emp[3].toString());
}
else if (ID.charAt(0) == 'P')
{
String first = input.nextLine();
String last = input.nextLine();
String ssn = input.nextLine();
Date DayOfBirth = new Date(input.nextInt(),input.nextInt(),input.nextInt());
Double Wage = input.nextDouble();
Double Pieces = input.nextDouble();
Emp[4] = new PieceWorker(first,last,ssn,DayOfBirth,ID,Wage,Pieces);
System.out.println(Emp[4].toString());
}
}
input.close();
}
}
我正在尝试读取的文件
S100
Sully
Ross
111-11-1111
8 15 1979
900.00
H205
Joe
Aggie
222-22-2222
3 6 1993
15.25
40
C102
Rev
Elee
333-33-3333
11 22 1985
20000
.065
B115
Johnny
Football
444-44-4444
06 28 1965
12000
.05
400
P206
Miss
Bizbee
555-55-5555
11 06 1977
1.25
1000
X
【问题讨论】: