为什么我会收到 InputMismatchException?

Why am I getting an InputMismatchException with?

我在 java 中创建了一个扫描仪来读取有关城市的数据文件。文件格式如下:

Abbotsford,2310,2
Adams,1967,1
Algoma,3167,2

阅读文件时,扫描每行的最后一项时出现 InputMismatchException(此项需要是 int)。

public void fileScanner(File toScan) throws FileNotFoundException {
            Scanner sc = new Scanner(toScan);
            sc.useDelimiter(",");
            System.out.println(sc.next());
            System.out.println(sc.nextInt());
            System.out.println(sc.nextInt());

关于为什么的任何想法?我想这与我使用“,”分隔符有关。

您使用的分隔符是逗号(,) 系统查找下一个逗号,它仅出现在 Adams 之后。所以系统的输入看起来像 2 Adams ,这显然不是 Int ,而是 String ,因此是 inputMisMatch.

如果你的数据如下所示,你的代码会很好用。

Abbotsford,2310,2,
Adams,1967,1,
Algoma,3167,2,

我还看到没有循环读取所有数据。您的代码将只读取第一行。

您只使用了一个分隔符,即 ,,但您的文件包含 \r\n,因此请尝试使用多个分隔符。另外,使用循环读取整个文件:-

Scanner sc = new Scanner(toScan);
        sc.useDelimiter(",|\r\n");
        while (sc.hasNext()) {
            System.out.println(sc.next());
            System.out.println(sc.nextInt());
            System.out.println(sc.nextInt());
        }

输出:-

Abbotsford
2310
2

Adams
1967
1

Algoma
3167
2