0

您好,我有一个文本文件,我正在尝试从中读取一组数字,该文件类似于:

st:ATTR1 20121011        0        0      127      122      -17

我试图使用扫描仪,使用空格作为分隔符,并读取第一个字符串,其余作为整数。但是每当我尝试运行它时,我都会收到此错误:

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 prog8.prog8.main(prog8.java:22)

我不确定为什么会这样,因为据我所知,这应该只允许我阅读下一个 int,而不必担心其他字符。

我的代码是:

package prog8;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class prog8 {

public static void main(String[] args) {
    File file = new File("files/Weather.txt");
    int date = 0;
    int prcp = 0;
    int snow = 0;
    int snwd = 0;
    int tmax = 0;
    int tmin = 0;

    try {
        Scanner reader = new Scanner(file).useDelimiter(" ");
        while (reader.hasNextLine()) {
            String station = reader.next();
            date = reader.nextInt();
            prcp = reader.nextInt();
            snow = reader.nextInt();
            snwd = reader.nextInt();
            tmax = reader.nextInt();
            tmin = reader.nextInt();
            System.out.printf("station: %s, date: %d, prcp: %d, snow: %d, snwd: %d, tmax: %d, tmin: %d", station, date, prcp, snow, snwd, tmax, tmin);

        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}
}

谁能告诉我为什么会这样?

4

1 回答 1

3

如果您将分隔符设置为单个空格,则不能使用多个空格。

删除.useDelimiter(" ");并且您的程序可以正常工作

于 2012-11-19T17:58:12.393 回答