我正在尝试使用以下代码从文本文件中读取一系列变量:
public static Book readBook(String pathname) throws IOException, InputMismatchException {
Scanner fl = new Scanner (new FileInputStream (fn));
int num = fl.nextInt();
double thePrice = 0;
String theAuthor = null;
String theTitle = null;
for (int i=0; i<=num; i++) {
theTitle = fl.nextLine();
theAuthor = fl.nextLine();
thePrice = fl.nextDouble();
}
System.out.print(num);
System.out.print(theTitle);
System.out.print(theAuthor);
fl.close();
return new Book(theTitle, theAuthor, thePrice);
}
File 包含一个用于 while 循环的数字,用于说明需要多少遍。文件如下所示:
2
name
author
10.00
name2
author2
12.00
但这会引发输入不匹配错误,由于某种原因将第一行读取为“name2”,从而弄乱了顺序并在代码达到双精度时导致错误。任何帮助,将不胜感激!
堆栈跟踪:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at Model.readBook(Model.java:36)