import java.io.*; /*原始代码 BufferedReader br=new BufferedReader(new FileReader("score.txt")) String line; while((line=br.readLine())!=null){ sum += Integer.parseInt(line) } br.close() */ //修改后的代码 public class score { public static void main(String[] args){ //使用try()-with-resources确保文件自动关闭 try(BufferedReader br=new BufferedReader(new FileReader("score.txt"))){ double sum=0; int count=0; String line; while((line=br.readLine())!=null){ try{ sum += Integer.parseInt(line); count++; } catch (NumberFormatException e) { System.out.println("数字格式错误"); } } //计算平均数 if (count>0){ double average=sum/count; System.out.println("平均分是"+average); } else{ System.out.println("计数不符合规范,没有平均数"); } } //最外层的catch catch (FileNotFoundException e){ System.out.println("文件不存在"); } //同样也是最外层的catch catch (IOException e){ System.out.println("读取文件发生错误"); } } }