From 49592abbcbd03c76b3a7ca714cc4c5298d280f63 Mon Sep 17 00:00:00 2001 From: Mengxinyao Date: Thu, 23 Apr 2026 16:20:50 +0800 Subject: [PATCH] =?UTF-8?q?feat(w7):W7-=E5=AD=9F=E9=91=AB=E5=9E=9A-2025060?= =?UTF-8?q?10204?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- w7/.DS_Store | Bin 0 -> 6148 bytes w7/Main.java | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 w7/.DS_Store create mode 100644 w7/Main.java diff --git a/w7/.DS_Store b/w7/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..5189d6eedae8fe9aa314998f1f98976a4359ab13 GIT binary patch literal 6148 zcmeHKF-`+P474Fd5KT(TeL*CCutcGtpyC5bpaDgsg8C}n#m`{Iwosx=8YCJtmh9Q} zdTw)5oMSWd#oN=h+04wQaH4%MjE(2?k)2h>fp9!yZZEdBcU#|WN7cs@LiG2IffxCe>@i@T4Q(s;(CfiAgt)oAI2w*=s`axE=Wx z<>oz6Q3^ scores = new ArrayList<>(); + + /** + * 从指定文件读取成绩 + * @param filename 文件名 + * @throws IOException 文件读取错误 + * @throws InvalidScoreException 成绩格式无效 + */ + public void loadScoresFromFile(String filename) throws IOException, InvalidScoreException { + scores.clear(); + try (BufferedReader reader = new BufferedReader(new FileReader(filename))) { + String line; + int lineNumber = 0; + while ((line = reader.readLine()) != null) { + lineNumber++; + line = line.trim(); + if (line.isEmpty()) continue; // 跳过空行 + + try { + int score = Integer.parseInt(line); + if (score < 0 || score > 100) { + throw new InvalidScoreException("第 " + lineNumber + " 行:成绩应在 0~100 之间,但得到 " + score); + } + scores.add(score); + } catch (NumberFormatException e) { + throw new InvalidScoreException("第 " + lineNumber + " 行:\"" + line + "\" 不是有效的整数"); + } + } + } + } + + /** + * 计算平均分 + * @return 平均分(保留两位小数) + * @throws IllegalStateException 如果没有有效成绩 + */ + public double calculateAverage() { + if (scores.isEmpty()) { + throw new IllegalStateException("没有可计算的有效成绩"); + } + int sum = scores.stream().mapToInt(Integer::intValue).sum(); + return Math.round((double) sum / scores.size() * 100) / 100.0; + } + + public int getScoreCount() { + return scores.size(); + } +} + +// =============== 主类 =============== +public class Main { + public static void main(String[] args) { + ScoreProcessor processor = new ScoreProcessor(); + + try { + processor.loadScoresFromFile("scores.txt"); + double average = processor.calculateAverage(); + System.out.printf("共读取 %d 条有效成绩,平均分:%.2f%n", + processor.getScoreCount(), average); + } catch (FileNotFoundException e) { + System.err.println("❌ 文件未找到:请确保 'scores.txt' 存在于当前目录。"); + } catch (IOException e) { + System.err.println("❌ 读取文件时发生 I/O 错误:" + e.getMessage()); + } catch (InvalidScoreException e) { + System.err.println("❌ 成绩数据格式错误:" + e.getMessage()); + } catch (IllegalStateException e) { + System.err.println("❌ 数据不足:" + e.getMessage()); + } + } +} \ No newline at end of file