public static void readStaffsFromFile() {
String inFileName = "startup.txt";
int numStaff, staffID;
String name, address;
Staff newStaff;
boolean fileExists;
Scanner inFile = null;
File databaseFile = new File(inFileName);
fileExists = databaseFile.exists();
if (fileExists) {
try {
inFile = new Scanner(databaseFile);
} catch (FileNotFoundException fnfe) {
JOptionPane.showMessageDialog(null, "The file startup.txt has just now been deleted.");
return; // cannot do anything more.
}
numStaff = inFile.nextInt();
inFile.nextLine();
for (int i = 0; i < numStaff; i++) {
staffID = inFile.nextInt();
name = inFile.nextLine();
address = inFile.nextLine();
// try{
newStaff = new Staff(staffID, name, address);
addStaff(newStaff);
// } catch (StaffException se)
// {
// System.out.println("Unable to add staff: " + name +
// " to the system.");
// }
}
}
JOptionPane.showMessageDialog(null, "System has been set up with default data from startup.txt.");
}
我有这个方法,当我尝试从main调用这个方法时,它给了我这个错误。
线程“main”中的异常java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at SystemStartUp.readStaffsFromFile(SystemStartUp.java:195)
at SystemStartUp.loadFromFile(SystemStartUp.java:160)
at StartUp.main(StartUp.java:9)
错误的错误行表明我的错误从“staffID = inFile.nextInt();
”
输入文件如下所示。
13
11111111
Chris Ling
999 Dandenong Road
22222222
Des Casey
100 Silly Drive
33333333
Maria Indrawan
90 Programming Road
44444444
Campbell Wilson
2/5 Database Street
55555555
Janet Fraser
21 Web Drive
66666666
Judy Sheard
34 Hos Road
77777777
Ngoc Minh
24 Message Street
88888888
Martin Atchinson
45 Martine Street
99999999
Aleisha Matthews
1/6 Admin Road
10101010
Denyse Cove
100 Reception Street
12121212
Cornelia Liou
232 Reception Road
23232323
Trudi Robinson
111 Manager Street
34343434
Henry Linger
2/4 HDR Street
答案 0 :(得分:0)
staffID
可能并不总是包含数字。请检查输入文件。
在staffID
之后,您必须添加inFile.nextLine();
以使用带有数字的行之后的新行字符。否则,您将在第二个循环中收到错误。