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

Java读取文本文件提取浮点数存入数组如何跳过特定字符串内容

问题原因分析

你现有代码报错的核心原因是:每行按空白符分割后得到的第一个元素是类似x,的字符串,无法直接转换为浮点数,触发NumberFormatException异常。同时你当前的分割逻辑没有处理逗号分隔符,也不符合你提供的文件格式规则。

解决方案

方案1:适配固定格式文件(推荐,适合你当前的文件结构)

你的文件每行固定为「标识, 浮点数」的格式,直接按逗号分割取第二部分处理即可,修改后的代码如下:

public static void readParameters() throws FileNotFoundException{
    // try-with-resources自动关闭资源,无需手动调用close
    try (Scanner inFile = new Scanner(new File(filename))) {
        ArrayList<Float> values = new ArrayList<>();
        
        while (inFile.hasNextLine()) {
            String line = inFile.nextLine().trim();
            // 跳过空行避免报错
            if (line.isEmpty()) continue;
            // 按逗号分割内容
            String[] parts = line.split(",");
            if (parts.length >= 2) {
                // 取第二部分去除前后空白后转浮点数
                float num = Float.parseFloat(parts[1].trim());
                values.add(num);
                System.out.println(num);
            }
        }
        // 遍历结束后values就是仅包含浮点数的集合
    }
}

方案2:通用浮点数提取(适配不确定格式的文件)

如果文件内容格式不固定,仅需要提取所有浮点数,可以用正则匹配的方式,过滤出所有符合浮点数规则的内容:

public static void readParameters() throws FileNotFoundException{
    // 匹配浮点数的正则,支持正负、整数、小数形式
    Pattern floatPattern = Pattern.compile("-?\\d+(\\.\\d+)?");
    try (Scanner inFile = new Scanner(new File(filename))) {
        ArrayList<Float> values = new ArrayList<>();
        
        while (inFile.hasNextLine()) {
            String line = inFile.nextLine().trim();
            if (line.isEmpty()) continue;
            Matcher matcher = floatPattern.matcher(line);
            // 提取当前行所有符合规则的浮点数
            while (matcher.find()) {
                float num = Float.parseFloat(matcher.group());
                values.add(num);
                System.out.println(num);
            }
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 04:54:04