import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class ScoreAvg { public static void main(String[] args) { String fileName = "scores.txt"; BufferedReader br = null; int sum = 0; int count = 0; // ======================== // 题目要求:try catch finally // ======================== try { // 1. 打开文件 br = new BufferedReader(new FileReader(fileName)); // 2. 读取每一行 String line; while ((line = br.readLine()) != null) { line = line.trim(); if (line.isEmpty()) continue; try { int score = Integer.parseInt(line); sum += score; count++; } catch (NumberFormatException e) { System.out.println("格式错误:" + line); } } // 3. 输出结果 System.out.println("总分:" + sum); System.out.println("平均分:" + (double) sum / count); } catch (IOException e) { // 异常处理 System.out.println("文件操作失败!"); e.printStackTrace(); } finally { // ======================== // finally:必须执行,关闭流! // 题目要求必须写这里! // ======================== try { if (br != null) { br.close(); System.out.println("流已关闭!"); } } catch (IOException e) { System.out.println("关闭失败!"); } } } }