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

Java使用扫描循环查找列表特定值时触发NumberFormatException问题

解决读取文件指定字符串下一行转Double时的NumberFormatException问题

问题根源分析

两种实现都存在多个致命问题,共同触发NumberFormatException:

  • Scanner初始化错误:new Scanner(filePath)是将字符串filePath作为输入源,而非读取对应路径的文件,正确做法是基于File对象初始化Scanner。
  • 路径格式错误:Windows文件路径需用双反斜杠\\或正斜杠/分隔,且你当前路径拼写错误(myiflepath应为myfilepath),正确路径示例:"C:\\myfilepath"。
  • 字符串比较错误(第二种实现):使用==比较字符串内容,应改用equals()方法,==仅比较对象引用。
  • 逻辑混乱(第二种实现):多次无意义调用scanner.nextLine(),导致指针跳过大量行,无法正确定位目标内容。
  • 未处理异常场景:两种实现都未处理“未找到目标字符串”或“目标字符串后无内容”的情况,会导致索引越界或取到无效内容。

修正后的实现一:基于List读取

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class constantb {
    // 修正路径格式与拼写
    static String filePath = "C:\\myfilepath";

    public static Double findDouble(String name) throws IOException {
        List<String> list = new ArrayList<>();
        // 基于File对象初始化Scanner,自动关闭资源
        try (Scanner constScanner = new Scanner(new File(filePath))) {
            while (constScanner.hasNextLine()) {
                // 去除行首尾空白,避免意外空格/换行干扰
                list.add(constScanner.nextLine().trim());
            }
        }

        int targetIndex = list.indexOf(name);
        // 校验目标字符串是否存在且下一行有效
        if (targetIndex == -1 || targetIndex + 1 >= list.size()) {
            throw new IllegalArgumentException("未找到目标字符串或目标字符串后无有效内容");
        }

        String valueStr = list.get(targetIndex + 1);
        System.out.println(valueStr);
        return Double.parseDouble(valueStr);
    }
}

修正后的实现二:直接使用Scanner遍历

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

public class constantc {
    // 修正路径格式与拼写
    static String filePath = "C:\\myfilepath";

    public static Double findDouble(String name) throws IOException {
        // 基于File对象初始化Scanner,自动关闭资源
        try (Scanner scanner = new Scanner(new File(filePath))) {
            while (scanner.hasNextLine()) {
                String currentLine = scanner.nextLine().trim();
                // 使用equals比较字符串内容
                if (currentLine.equals(name)) {
                    // 校验目标字符串后是否有内容
                    if (!scanner.hasNextLine()) {
                        throw new IllegalArgumentException("目标字符串后无有效内容");
                    }
                    String valueStr = scanner.nextLine().trim();
                    return Double.parseDouble(valueStr);
                }
            }
            // 遍历结束未找到目标
            throw new IllegalArgumentException("未找到目标字符串");
        }
    }
}

额外说明

  • 使用try-with-resources语法自动关闭Scanner,避免资源泄漏,无需手动调用close()。
  • 读取每行时调用trim(),去除行首尾空白字符,彻底避免因意外空格、换行符导致的NumberFormatException。
  • 增加异常判断逻辑,抛出明确的非法参数异常,便于快速定位问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 14:52:20