import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; /** * 读取scores.txt文件计算平均分 * 包含完整异常处理与资源自动关闭 */ public class ScoreAverage { public static void main(String[] args) { // 初始化总和与计数 int sum = 0; int count = 0; // try-with-resources 自动关闭流,无需手动调用 close() try (BufferedReader br = new BufferedReader(new FileReader("scores.txt"))) { String line; // 逐行读取文件 while ((line = br.readLine()) != null) { // 去除行首尾空白(避免空行/空格干扰) line = line.trim(); // 跳过空行 if (line.isEmpty()) { continue; } // 数字格式转换与累加 sum += Integer.parseInt(line); count++; } // 计算并输出平均分(处理无数据情况) if (count > 0) { double average = (double) sum / count; System.out.printf("总分:%d,人数:%d,平均分:%.2f%n", sum, count, average); } else { System.out.println("文件中无有效成绩数据"); } } catch (java.io.FileNotFoundException e) { // 捕获:文件不存在/无法读取 System.out.println("错误:文件未找到 - " + e.getMessage()); } catch (NumberFormatException e) { // 捕获:行内容非有效整数 System.out.println("错误:数据格式非有效整数 - " + e.getMessage()); } catch (IOException e) { // 捕获:读取文件时的IO异常 System.out.println("错误:读取文件失败 - " + e.getMessage()); } } }