import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class SafeScoreAvg { public static void main(String[] args) { String filePath = "scores.txt"; int sum = 0; int count = 0; // 1. 使用 try-with-resources,自动关闭流 try (BufferedReader br = new BufferedReader(new FileReader(filePath))) { String line; while ((line = br.readLine()) != null) { // 去掉前后空格,跳过空行 line = line.trim(); if (line.isEmpty()) { continue; } // 2. 处理数字格式错误 try { int score = Integer.parseInt(line); sum += score; count++; } catch (NumberFormatException e) { System.err.println("⚠️ 警告:跳过无效成绩行(非数字内容):" + line); } } // 计算并输出结果 if (count == 0) { System.out.println("ℹ️ 提示:文件中没有有效成绩数据"); } else { double average = (double) sum / count; System.out.printf("✅ 平均分:%.2f%n", average); } } catch (IOException e) { // 3. 处理文件不存在、读取错误等IO异常 System.err.println("❌ 文件操作失败:" + e.getMessage()); e.printStackTrace(); } } }