我的代码问题似乎应该运行得很好。
public void inputFile() {
Scanner reader = null;
try {
reader = new Scanner( new File ("parts.dat"));
reader.useDelimiter("\\,|\\n");
while(reader.hasNext()) {
System.out.println(reader.next());
System.out.println(reader.next());
System.out.println(reader.nextDouble());
System.out.println(reader.nextInt()); //InputMismatchException
}
}
catch(IOException e) {
}
finally {
reader.close();
}
}
当我运行代码时,我得到以下输出:
137B245
1/4" bolt
0.59
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.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at lab02d.inputFile(lab02d.java:25)
at lab02d.main(lab02d.java:11)
parts.dat包含:
137B245,1/4" bolt,.59,12
137N245,1/4" nut,.29,12
137B246,1/2" bolt,.79,12
137N246,1/2" nut,.39,25
139S128,1/8" wood screw,.19,8
139S129,1/4" wood screw,.22,4
139S130,1/2" wood screw,.35,16
145W321,1/8" washer,.12,5
145W322,1/4" washer,.14,6
145W323,1/2" washer,.18,9
我已经尝试了几种方法来尝试使这些代码正常工作。我尝试过使用Integer.parseInt(reader.next()),但这只会引发另一个异常。我也尝试过更改文本文件编码,但这也没有解决任何问题。
答案 0 :(得分:1)
我很确定你的文件在这些行的末尾有额外的空格,阻止扫描程序解析看似合理的int。就像回车一样。将分隔符调整为如下所示,然后重试:
Array
(
[0] => HTTP/1.1 200 OK
[1] => Server: nginx/1.10.1
[2] => Content-Type: application/json
[3] => Connection: close
[4] => Cache-Control: private, must-revalidate
[5] => Date: Wed, 02 Nov 2016 14:47:36 GMT
[6] => pragma: no-cache
[7] => expires: -1
[8] => X-Debug-Token: fadeb4
[9] => Strict-Transport-Security: max-age=31536000; includeSubdomains;
)