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

Android开发:读取TXT文件指定字段匹配结果异常求助

问题分析与解决方案

嘿,我一眼就瞅出你代码里的问题啦!核心bug出在文件读取的逻辑上——你完全误解了文本文件的格式,导致不管输入什么值,程序都没法正确匹配到对应的行。

问题根源

你的文本文件每一行是四个值用空格分隔(比如10 60 40 Z185-.......),但你的foo()方法里每次循环会调用br.readLine()四次:把第一行当成currentPetrol,第二行当成currentDiesel,第三行当成currentAir,第四行当成currentResult。这相当于把连续4行的内容拆成了一组匹配条件,完全不符合你的文件结构,自然永远匹配不到正确的内容,甚至会提前读完文件返回错误结果。

修正后的解决方案

我们需要修改读取逻辑:每次读取一行,然后把这一行按空格分割成4个字段,再依次对比前三个字段和用户输入的值,匹配成功就返回第四个字段。

另外,我还优化了资源管理(用try-with-resources自动关闭流,避免资源泄漏),以及增加了输入的整数转换对比(避免字符串对比的潜在问题,比如用户输入多余空格)。

修改后的foo()方法代码如下:

private String foo(String filename, String petrolInput, String dieselInput, String airInput) {
    // 先把输入转成整数,避免字符串对比的问题
    Integer petrol = null;
    Integer diesel = null;
    Integer air = null;
    try {
        petrol = Integer.parseInt(petrolInput.trim());
        diesel = Integer.parseInt(dieselInput.trim());
        air = Integer.parseInt(airInput.trim());
    } catch (NumberFormatException e) {
        e.printStackTrace();
        return "Invalid input! Please enter numbers.";
    }

    // 使用try-with-resources自动关闭流,无需手动close
    try (FileReader fileReader = new FileReader(new File(context.getFilesDir(), filename));
         BufferedReader br = new BufferedReader(fileReader)) {

        String line;
        while ((line = br.readLine()) != null) {
            // 按任意数量空格分割每行内容,适配可能的多空格场景
            String[] parts = line.trim().split("\\s+");
            // 确保一行有4个有效字段
            if (parts.length != 4) {
                continue; // 跳过格式错误的行
            }

            try {
                Integer currentPetrol = Integer.parseInt(parts[0]);
                Integer currentDiesel = Integer.parseInt(parts[1]);
                Integer currentAir = Integer.parseInt(parts[2]);
                String currentResult = parts[3];

                // 对比数值是否匹配
                if (currentPetrol.equals(petrol) && currentDiesel.equals(diesel) && currentAir.equals(air)) {
                    return currentResult; // 匹配成功,直接返回结果
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
                continue; // 跳过数值格式错误的行
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        return "Error reading file!";
    }

    return "No entry found!"; // 遍历完所有行都没匹配到
}

额外优化建议

  • 给你的三个EditText设置输入类型为数字:在XML里添加android:inputType="number",这样用户只能输入数字,避免格式转换错误。
  • 可以在点击按钮时先检查输入是否为空,比如:
    if (petrol.isEmpty() || diesel.isEmpty() || air.isEmpty()) {
        textViewResult.setText("Please fill all fields!");
        return;
    }
    
  • 如果你的文本文件里的字段可能包含多个空格,用split("\\s+")可以匹配任意数量的空格,比split(" ")更鲁棒。

这样修改后,当用户输入petrol:10、diesel:60、air:40时,程序就会正确找到对应的行,返回Z185-...啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:32:23