From 7de250525555526b21bd5cdc2c88c08e229bdd00 Mon Sep 17 00:00:00 2001 From: zhouzihao Date: Mon, 20 Apr 2026 22:07:27 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=8A=E4=BC=A0=E6=96=87=E4=BB=B6=E8=87=B3?= =?UTF-8?q?=20'W7=E5=91=A8=E6=A2=93=E6=B5=A9202506050319'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- W7周梓浩202506050319/score.java | 48 ++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 W7周梓浩202506050319/score.java diff --git a/W7周梓浩202506050319/score.java b/W7周梓浩202506050319/score.java new file mode 100644 index 0000000..9b61fdd --- /dev/null +++ b/W7周梓浩202506050319/score.java @@ -0,0 +1,48 @@ +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("读取文件发生错误"); + } + } +} \ No newline at end of file