行尾扫描器InputMismatchException

时间:2018-12-24 15:31:57

标签: java

我正在尝试使用扫描仪读取此文件:

    Movie1 Nicholson 1985
    Movie2 Jackson 1975 action,adventure 

但是,我的扫描仪在该行的末尾抛出了java.util.InputMismatchException。我尝试使用sc.nextLine(),但没有成功。预期的行为是将文本文件中的year加载到名为year的整数中,创建一个新对象,然后移至下一行。谢谢!我的代码如下:

public static ListOfDVDs fromFile(String fileName) {
    ListOfDVDs list = new ListOfDVDs();
    Scanner sc = null;
    String name = null;
    int year = 0;
    String director = null;
    try {
        sc = new Scanner(new File(fileName));
        while (sc.hasNext()) {
            name = sc.next();
            director = sc.next();
            year = sc.nextInt(); //exception here
            DVD dvd = new DVD(name, year, director);
            list.add(dvd);
        }

    } catch (FileNotFoundException e) {
        System.err.println("file not found");
    } finally {
        if (sc != null) {
            sc.close();
        }
    }

    return list;
}

1 个答案:

答案 0 :(得分:0)

如果您在评论中提到过,则可以确保文件格式正确,
然后我建议逐行读取文件,并使用空格作为分隔符来拆分每一行。
然后从保存单个值的数组中获取每个值。
还有一件事,是否有第一行包含列标题的情况?如果是这样,则读数必须从第二行开始。

public static ListOfDVDs fromFile(String fileName) {
    ListOfDVDs list = new ListOfDVDs();

    String name = null;
    int year = 0;
    String director = null;

    Scanner sc = null;
    try {
        sc = new Scanner(new File(fileName));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return list;
    }

    while (sc.hasNextLine()) {
        String[] tokens = sc.nextLine().trim().split(" ");
        if (tokens.length >= 3) {
            name = tokens[0];
            director = tokens[1];
            try {
                year = Integer.parseInt(tokens[2]);
            } catch (NumberFormatException e) {
                e.printStackTrace();
                year = 0;
            }
            DVD dvd = new DVD(name, year, director);
            list.add(dvd);
        }
    }
    sc.close();

    return list;
}