我的扫描仪在读取文件时出现问题。它假设在逗号后跟空格或创建新行时创建一个新标记,但在 4 个标记之后,它抛出 NoSuchElementException。
private Map<String, Double> createElementMassMap(String filePath) {
Map<String, Double> elementMap = new HashMap<>();
try (Scanner sc = new Scanner(new FileReader(filePath))) {
sc.useDelimiter(Pattern.compile("(, ) | (\r\n)"));
sc.useLocale(Locale.US);
while(sc.hasNext()) {
String name = sc.next();
System.out.println(name);
double mass = sc.nextDouble();
System.out.println(mass);
elementMap.put(name, mass);
}
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(self, "Error loading ElementMasses file.", "IOException", JOptionPane.ERROR_MESSAGE);
}
return elementMap;
}
这是它试图读取的文件
H, 1.00
O, 16.00
我确保文件中没有空行。
最佳答案
嗯,我是个白痴,我的模式搞砸了。
//instead of
sc.useDelimiter(Pattern.compile("(, ) | (\r\n)"));
//it should be this
sc.useDelimiter(Pattern.compile("(, )|(\r\n)"));
谢谢你们提供的有用答案!
关于来自扫描仪的 java.util.NoSuchElementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32072989/