From e95d7ecd943c8f546b1aad83d30fc79bd8742204 Mon Sep 17 00:00:00 2001 From: ZhangJinxuan <2194936226@qq.com> Date: Mon, 27 Apr 2026 14:20:44 +0800 Subject: [PATCH] =?UTF-8?q?=E7=AC=AC=E4=B8=80=E6=AC=A1=E6=8F=90=E4=BA=A4?= =?UTF-8?q?=EF=BC=9A=E4=B8=8A=E4=BC=A0w7=E6=96=87=E4=BB=B6=E5=A4=B9?= =?UTF-8?q?=E6=89=80=E6=9C=89=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ScoreAverge.java | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 ScoreAverge.java diff --git a/ScoreAverge.java b/ScoreAverge.java new file mode 100644 index 0000000..3716739 --- /dev/null +++ b/ScoreAverge.java @@ -0,0 +1,46 @@ +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; + +public class ScoreCalculator { + public static void main(String[] args) { + String fileName = "scores.txt"; + int sum = 0; + int count = 0; + + // try-with-resources 自动关闭流,无需手动写 br.close() + try (BufferedReader br = new BufferedReader(new FileReader(fileName))) { + String line; + while ((line = br.readLine()) != null) { + // 去除字符串前后空格,避免空行或空格影响解析 + line = line.trim(); + if (line.isEmpty()) { + continue; // 跳过空行 + } + + try { + // 解析成绩为整数 + int score = Integer.parseInt(line); + sum += score; + count++; + } catch (NumberFormatException e) { + // 数字格式错误处理 + System.err.println("警告:无法解析成绩 '" + line + "',跳过该数据"); + } + } + + // 计算平均分 + if (count > 0) { + double average = (double) sum / count; + System.out.println("平均分:" + average); + } else { + System.out.println("文件中没有有效成绩数据"); + } + + } catch (IOException e) { + // 文件不存在、读取错误处理 + System.err.println("读取文件时发生错误:" + e.getMessage()); + e.printStackTrace(); + } + } +} \ No newline at end of file