使用定界符分隔模式

Use delimiter to separate a pattern

我有一个文本文件,我正在尝试使用 Scanner 读取字符串和整数输入。我需要用逗号分隔数据,还有换行符的问题。这是文本文件内容:

John T Smith, 90
Eric K Jones, 85

我的代码:

public class ReadData {
  public static void main(String[] args) throws Exception {
      java.io.File file = new java.io.File("scores.txt");
      Scanner input = new Scanner(file);
      input.useDelimiter(",");
      while (input.hasNext()) {
          String name1 = input.next();
          int score1 = input.nextInt();
          System.out.println(name1+" "+score1);
      }
      input.close();
  }
}

异常:

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 ReadData.main(ReadData.java:10)

将 class java.util.Scanner 的分隔符设置为逗号 (,) 意味着每次调用方法 next() 都将读取 all 到下一个逗号的数据,包括换行符。因此,对 nextInt 的调用会在下一行读取分数 加上 名称,这不是 int。因此 InputMismatchException.

只需阅读整行并用逗号分隔 (,)。
(注:以下代码使用try-with-resources

public class ReadData {
    public static void main(String[] args) throws Exception {
        java.io.File file = new java.io.File("scores.txt");
        try (Scanner input = new Scanner(file)) {
//            input.useDelimiter(","); <- not required
            while (input.hasNextLine()) {
                String line = input.nextLine();
                String[] parts = line.split(",");
                String name1 = parts[0];
                int score1 = Integer.parseInt(parts[1].trim());
                System.out.println(name1+" "+score1);
            }
        }
    }
}

使用 ",|\n" RegExp 分隔符:

public class ReadData {
  public static void main(String[] args) throws Exception {
    java.io.File file = new java.io.File("scores.txt");
    Scanner input = new Scanner(file);
    input.useDelimiter(",|\n");
    while (input.hasNext()) {
        String name1 = input.next();
        int score1   = Integer.parseInt(input.next().trim());
        System.out.println(name1+" "+score1);
    }
    input.close();
  }
}

试试这个。

String text = "John T Smith, 90\r\n"
            + "Eric K Jones, 85";
Scanner input = new Scanner(text);
input.useDelimiter(",\s*|\R");
while (input.hasNext()) {
    String name1 = input.next();
    int score1 = input.nextInt();
    System.out.println(name1+" "+score1);
}
input.close();

输出:

John T Smith 90
Eric K Jones 85