You need to enable JavaScript to run this app. Java读取文件数据存入数组时抛出NumberFormatException如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Java读取文件数据存入数组时抛出NumberFormatException如何解决

酒店客房预订程序文件读取 NumberFormatException 排查修复指南

核心定位逻辑

  • 先抓异常堆栈的第一行自定义代码位置:控制台抛出NumberFormatException时,堆栈会直接定位到你执行字符串转数值的代码行,不需要无目标排查整个读取流程。
  • 逐行匹配解析链路和源文件数据:你当前的解析逻辑是逐行拆分后依次转换int型房号、double型房价,这两个位置是唯一会触发数值转换的节点,重点校验对应取到的字符串值。
  • 排查高频错位问题:
    • 拆分字段时分隔符匹配失效,导致取到的字段和预期位置错位(比如本该取房号的位置拿到了房型字符串,直接转int抛错)
    • 文本文件里的数值混了全角字符、前后空格、非数值干扰(比如全角数字“302”、带人民币符号的价格“¥399”)
    • 文件存在空行、字段数不足6个,导致数组取值越界后拿到空字符串做转换

可直接复用的容错读取代码

// 带容错校验的rooms.txt读取逻辑,适配你的Room数组存储需求
private static final int ROOM_COUNT = 50;
private static Room[] roomArray = new Room[ROOM_COUNT];
private static int index = 0;

public static void loadRooms() {
    int lineCount = 0;
    try (Scanner scanner = new Scanner(new FileReader("rooms.txt"))) {
        while (scanner.hasNextLine()) {
            lineCount++;
            String rawLine = scanner.nextLine().trim();
            // 跳过空行,避免空值转换报错
            if (rawLine.isEmpty()) continue;
            // 按逗号拆分,自动吞掉逗号后的多余空格
            String[] fields = rawLine.split(",\\s*");
            // 校验字段数量,不匹配直接打日志跳过,不硬转值
            if (fields.length != 6) {
                System.out.printf("第%d行格式错误,需6个字段,实际为%d个,行内容:%s%n", lineCount, fields.length, rawLine);
                continue;
            }
            // 逐段提取值,做单独转换校验
            String roomNumRaw = fields[0].trim();
            String type = fields[1].trim();
            String priceRaw = fields[2].trim();
            int roomNum;
            double price;
            try {
                roomNum = Integer.parseInt(roomNumRaw);
                price = Double.parseDouble(priceRaw);
            } catch (NumberFormatException e) {
                System.out.printf("第%d行数值转换失败:房号字段值=[%s],价格字段值=[%s]%n", lineCount, roomNumRaw, priceRaw);
                continue;
            }
            boolean hasBalcony = Boolean.parseBoolean(fields[3].trim());
            boolean hasLounge = Boolean.parseBoolean(fields[4].trim());
            String isReserved = fields[5].trim();
            // 构造Room实例存入数组
            if (index < ROOM_COUNT) {
                roomArray[index++] = new Room(roomNum, type, price, hasBalcony, hasLounge, isReserved);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

避坑注意事项

  • 不要把所有数值转换嵌在Room构造方法的参数里写一行,否则异常抛出时无法快速区分是房号转换失败还是房价转换失败。
  • 不要默认源文本文件的格式完全合规,课设场景下手动编辑文本时多打空格、漏逗号、错打全角字符是高频问题,必须加前置校验。
  • 拆分字段时优先使用正则split(",\\s*")替代普通的split(","),可以兼容逗号后带空格的不规范格式。

内容的提问来源于stack exchange,提问作者Joseph Michael

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.13 08:36:06