为什么我会收到一个InputMismatchException错误?

huangapple go评论31阅读模式
英文:

Why am I getting an InputMismatchException with?

问题

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

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

在读取文件时,当扫描每行的最后一项时(此项应为整数),会出现InputMismatchException异常。

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());
}

对于为什么会出现这种情况,你有什么想法吗?我想可能与我使用的","分隔符有关。

英文:

I created a Scanner in java to read through a file of data regarding a city. The file is formatted as such:

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

When reading through the file, I get an InputMismatchException when scanning the last item on each line (This item needs to be an 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());

Any ideas as to why? I'd imagine it has something to do with my use of the "," delimiter.

答案1

得分: 3

你只使用了一个分隔符,即,,但你的文件中包含了\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
英文:

You are using only one delimiter i.e. , but your file contains \r or \n so try to use multiple delimiters. Also, use a loop to read the entire file:-

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());
        }

OUTPUT:-

Abbotsford
2310
2

Adams
1967
1

Algoma
3167
2

答案2

得分: 1

以下是翻译好的内容:

分隔符您正在使用逗号(,)
系统寻找下一个逗号,该逗号仅在Adams之后。因此,系统的输入看起来像是2 Adams,显然不是Int,而是String,因此会出现输入不匹配的错误。

如果您将您的数据设置如下,您的代码将能够正常工作。

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

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

英文:

The delimiter you're using is comma(,)
The system looks for the next comma, which comes only after Adams. So the input for the system looks like 2 Adams which is obviously not an Int , rather a String and hence the inputMisMatch.

If you make your data something like below, your code would work great.

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

Also I see there's no loop to read all the data. Your code will read just the first line.

huangapple
  • 本文由 发表于 2020年4月4日 12:38:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/61023823.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定