You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

读取文件触发InputMismatchException,如何正确读取填充Train数组?

解决读取文件时的InputMismatchException问题

我来帮你分析一下问题出在哪儿,以及怎么修复它:

问题根源

你的代码里用了console.nextLine()来读取火车名称,但这里有个关键的坑:nextInt()方法只会读取整数,不会处理整数后面的换行符或空格。当你读完totalTrains后,Scanner的指针停在10后面的空格位置,这时候调用console.nextLine()会读取从当前指针到换行符之间的内容——也就是一段空字符串(因为你的示例文件里所有数据都是连续用空格分隔的)。接下来你尝试用console.nextInt()读取"Train"这个字符串,自然就触发InputMismatchException了。

另外,你循环末尾的console.nextLine()也是多余的,会导致跳过部分有效数据。

修复方案

因为你的火车名称(比如Train、Train2)都是没有空格的单词语句,所以应该用console.next()来读取火车名称。next()方法会自动跳过前面的空白(空格、换行等),然后读取到下一个空白为止的字符串,完全匹配你的文件格式。

修改后的代码如下:

public void fillArray(String info) {
    try {
        File f = new File(info);
        Scanner console = new Scanner(f);
        
        distance = console.nextInt();
        int totalTrains = console.nextInt();
        
        // 务必初始化trains数组,避免空指针异常
        trains = new Train[totalTrains];
        
        for(int i = 0; i < totalTrains; i++){
            // 用next()代替nextLine()读取火车名称
            String trainName = console.next();
            Time arrival = new Time(console.nextInt(), console.nextInt());
            Time departure = new Time(console.nextInt(), console.nextInt());
            trains[i] = new Train(trainName, departure, arrival, distance);
        }
        console.close(); // 记得关闭Scanner资源
    } catch (FileNotFoundException e) {
        System.out.println("Cannot locate File");
    } catch (InputMismatchException e) {
        // 可选:添加调试信息,方便定位错误位置
        System.out.println("输入格式不匹配,当前读取的内容:" + console.next());
        e.printStackTrace();
    }
}

额外说明

如果未来你的火车名称需要包含空格(比如"Super Express Train"),那建议调整文件格式:让每列火车的信息单独占一行,比如:

650 10
Train 23 40 12 09
Train2 02 24 12 15
...

这时候就需要用nextLine()了,但要注意在读取totalTrains后调用一次console.nextLine()来消耗掉第一行末尾的换行符,然后循环里每次读取一行,再拆分该行的内容。

内容的提问来源于stack exchange,提问作者Katrina Nygren

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:14:19