diff --git a/w7/SafeScoreAvg.class b/w7/SafeScoreAvg.class new file mode 100644 index 0000000..4d9fd4c Binary files /dev/null and b/w7/SafeScoreAvg.class differ diff --git a/w7/SafeScoreAvg.java b/w7/SafeScoreAvg.java new file mode 100644 index 0000000..7ffae8e --- /dev/null +++ b/w7/SafeScoreAvg.java @@ -0,0 +1,45 @@ +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(); + } + } +} \ No newline at end of file diff --git a/w7/scores.txt b/w7/scores.txt new file mode 100644 index 0000000..cb5b006 --- /dev/null +++ b/w7/scores.txt @@ -0,0 +1,24 @@ +85 +92 +78 +95 +88 +75 +90 +82 +96 +89 + +70 +88 +abc +93 +79 +84 +91 +缺考 +87 +76 +99 +81 +94 diff --git a/w7/屏幕截图 2026-04-27 112423.png b/w7/屏幕截图 2026-04-27 112423.png new file mode 100644 index 0000000..b358ae4 Binary files /dev/null and b/w7/屏幕截图 2026-04-27 112423.png differ