java—使用分隔符分隔模式

whitzsjs  于 2021-07-09  发布在  Java
关注(0)|答案(3)|浏览(437)

我有一个文本文件,我试图读取字符串和整数输入使用 Scanner . 我需要用逗号分隔数据,还有换行符的问题。以下是文本文件内容:
约翰t史密斯,90岁
埃里克·琼斯,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)
sq1bmfud

sq1bmfud1#

试试这个。

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
3pvhb19x

3pvhb19x2#

设置类的分隔符 java.util.Scanner 逗号( , )意味着每次调用 next() 将读取直到下一个逗号的所有数据,包括换行符。因此呼吁 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);
            }
        }
    }
}
8zzbczxx

8zzbczxx3#

使用 ",|\\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();
  }
}

相关问题