import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class ScoreAverage { public static void main(String[] args) { // 1. 定义变量:总分、有效成绩数量 int sum = 0; int count = 0; // 2. 使用 try-with-resources 自动关闭流,确保文件一定被关闭 try (BufferedReader br = new BufferedReader(new FileReader("scores.txt"))) { String line; while ((line = br.readLine()) != null) { // 去除首尾空格,避免空行或空格干扰 line = line.trim(); if (line.isEmpty()) { continue; // 跳过空行 } // 3. 解析数字并累加 int score = Integer.parseInt(line); sum += score; count++; } // 4. 计算并输出平均分(避免除以0) if (count > 0) { double average = (double) sum / count; System.out.println("读取到 " + count + " 个成绩"); System.out.printf("总分:%d,平均分:%.2f%n", sum, average); } else { System.out.println("文件中没有有效成绩数据"); } // 异常1:文件不存在/路径错误 } catch (IOException e) { System.out.println("文件读取错误:" + e.getMessage()); System.out.println("请检查 scores.txt 文件是否存在,或路径是否正确"); // 异常2:数字格式错误(比如文件里有非数字内容) } catch (NumberFormatException e) { System.out.println("数据格式错误:文件中包含无法解析为整数的内容"); System.out.println("错误详情:" + e.getMessage()); // 兜底异常,捕获其他意外错误 } catch (Exception e) { System.out.println("程序发生意外错误:" + e.getMessage()); e.printStackTrace(); } } }