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

无需数组实现TXT文件列总和与平均值计算的代码优化问询

优化无数组情况下列总和与平均值计算的Java代码

需求说明

作业要求:在不使用数组的前提下,获取文本文件中某一列的总和,再除以10得到平均值。

输入文本文件内容

86 89 98
78 83 93
93 76 89
95 80 93
64 79 95
89 63 73
71 89 96
75 87 78
88 92 91
93 82 87

原代码及问题

原代码存在效率冗余和健壮性不足的问题:

File f = new File("input.txt");
Scanner scan = new Scanner(f);
int columns = 0;
int sum = 0;
while (scan.hasNextLine()) {
    columns = scan.nextInt();
    System.out.println(columns);
    scan.nextInt();
    scan.nextInt();
    sum += columns;
}
scan.close();
System.out.println("Average of Column 1: " + sum / 10);

输出结果:Average of Column 1: 83

优化方案及代码

优化点说明

  • 移除无意义的调试打印,减少IO开销
  • 用try-with-resources自动管理资源,避免手动关闭导致的泄漏
  • 放弃硬编码行数,统计有效数据行数,适配文件行数变化
  • 加入异常处理,兼容文件缺失、数据格式异常等情况
  • 支持灵活指定目标列,无需修改核心逻辑
  • 使用浮点型计算平均值,避免整数除法的精度丢失

优化后的代码

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

public class ColumnAverage {
    public static void main(String[] args) {
        int targetColumn = 1; // 可修改为目标列(从1开始计数)
        int sum = 0;
        int validRowCount = 0;

        try (Scanner scan = new Scanner(new File("input.txt"))) {
            while (scan.hasNextLine()) {
                String[] rowData = scan.nextLine().trim().split("\\s+");
                // 检查当前行是否包含目标列
                if (rowData.length >= targetColumn) {
                    sum += Integer.parseInt(rowData[targetColumn - 1]);
                    validRowCount++;
                }
            }
        } catch (FileNotFoundException e) {
            System.err.println("错误:未找到输入文件 - " + e.getMessage());
            return;
        } catch (NumberFormatException e) {
            System.err.println("错误:数据格式异常 - " + e.getMessage());
            return;
        }

        if (validRowCount == 0) {
            System.out.println("无有效数据可计算");
            return;
        }
        double average = (double) sum / validRowCount;
        System.out.printf("第%d列的平均值:%.2f%n", targetColumn, average);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 17:48:30