从文件中读取两个 Int 值的问题

Issue with Reading two Int values from a file

我有包含以下数据的文件

A,8,43
B,7,42,
C,9,34

我正在使用下面的代码读取数据

Scanner input = new Scanner(new File("D:\test.txt"));
input.useDelimiter(",|\n");  
while(input.hasNext()) {
   String name = input.next();
   int age = input.nextInt();
   int height = input.nextInt();

当我执行程序时出现 InputMisMatch 异常, 有什么错误请指教

在第二行的末尾你有 , 和行分隔符(我假设 \n)这意味着你在这两个分隔符之间有空元素。

所以在第三次迭代中

String name = input.next();  
int age = input.nextInt();
int height = input.nextInt();

input.next(); 正在消耗 "",这意味着 input.nextInt() 将尝试消耗 C

要解决此问题,您可以将分隔符设置为 一个或多个 逗号和行分隔符的组合,例如

input.useDelimiter("(,|\n)+");

为了进一步改进您的代码,而不是 \n,您可以使用 Java 8 中添加的 \R(或早期版本中的 \r|\n)来处理所有行分隔符,因为目前您不将 \r 视为分隔符,因此可以将其视为有效标记。

所以更好的解决方案是使用

input.useDelimiter("(,|\R)+"); //for readability

甚至

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

问题出在useDelimiter方法的使用上。此方法接受 正则表达式 作为参数。你不能只说 ,|\n 来表示 "comma or new line"。有rules.

你应该传入的是"[,\n]+"。这意味着 "one or more characters in the following set: [comma, new line character]".

对于您当前传递的正则表达式 ,|\n,这意味着定界符应该是 ,\n,但不能同时是两者。所以当它遇到第二行时:

B,7,42,

事情是这样的:

  • next 读取 "B"
  • nextInt 读作“7”
  • nextInt 读作“42”
  • next 读取“,”和新行之间的空字符串。
  • nextInt 现在尝试读取下一个标记 "C",但它不能。
  • 异常!

我会做不同的事情——使用一个扫描器来解析文件的每一行,并使用嵌套在 while 循环中的第二个扫描器从第一个扫描器获得的行中提取标记或数据。例如:

String filePath = "D:\test.txt";
File file = new File(filePath);

// use try-with-resources
try (Scanner input = new Scanner(file)) {
    while (input.hasNextLine()) {
        String line = input.nextLine();
        Scanner lineScanner = new Scanner(line);
        lineScanner.useDelimiter("\s*,\s*"); // get comma and any surrounding whitespace if present
        String name = "";
        int age = 0;
        int height = 0;
        if (lineScanner.hasNext()) {
            name = lineScanner.next();
        } // else ... throw exception?
        if (lineScanner.hasNextInt()) {
            age = lineScanner.nextInt();
        } // else ... throw exception?
        if (lineScanner.hasNextInt()) {
            height = lineScanner.nextInt();
        } // else ... throw exception?

        // use name, age, height here
        System.out.printf("%s %s %s%n", name, age, height);

        lineScanner.close(); // don't waste resources -- return them
    }
} catch (IOException e) {
    e.printStackTrace();
}