gpt4 book ai didi

java - Scanner.nextInt() 在读取整数时抛出 InputMismatchException

转载 作者:行者123 更新时间:2023-11-30 10:36:56 25 4
gpt4 key购买 nike

我的代码有问题,看起来它应该可以完美运行。

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()),但这只会引发另一个异常。我也尝试过更改文本文件编码,但这也没有解决任何问题。

最佳答案

我相当确定您的文件在这些行的末尾有额外的空白,阻止扫描器解析看起来像合理 int 的内容。就像回车一样。将分隔符调整为如下所示,然后重试:

reader.useDelimiter("[\\,\\n\\r]+");

关于java - Scanner.nextInt() 在读取整数时抛出 InputMismatchException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40382074/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com