From 6c0c372789afbe411ab9e4c30ec3da4612adb1de Mon Sep 17 00:00:00 2001 From: Fuyuxinge <1876397977@qq.com> Date: Tue, 21 Apr 2026 20:53:20 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=8A=E4=BC=A0=E8=87=B3w7=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E5=A4=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- w7/ScoreAvg.java | 19 +++++++++++++++++++ w7/ScoreAvg2.java | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 w7/ScoreAvg.java create mode 100644 w7/ScoreAvg2.java diff --git a/w7/ScoreAvg.java b/w7/ScoreAvg.java new file mode 100644 index 0000000..ef862d3 --- /dev/null +++ b/w7/ScoreAvg.java @@ -0,0 +1,19 @@ +package w7; + +import java.io.BufferedReader; +import java.io.FileReader; + +public class ScoreAvg { + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new FileReader("scores.txt")); + String line; + int sum = 0; + int count = 0; + while ((line = br.readLine()) != null) { + sum += Integer.parseInt(line); + count++; + } + br.close(); + System.out.println((double) sum / count); + } +} \ No newline at end of file diff --git a/w7/ScoreAvg2.java b/w7/ScoreAvg2.java new file mode 100644 index 0000000..eb8a263 --- /dev/null +++ b/w7/ScoreAvg2.java @@ -0,0 +1,36 @@ +package w7; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; + +public class ScoreAvg2 { + public static void main(String[] args) { + String path = "scores.txt"; + int sum = 0; + int count = 0; + + try (BufferedReader br = new BufferedReader(new FileReader(path))) { + String line; + while ((line = br.readLine()) != null) { + + try { + sum += Integer.parseInt(line); + count++; + } catch (NumberFormatException e) { + System.err.println("跳过无效数字行:" + line); + } + } + + if (count > 0) { + System.out.printf("平均分:%.2f%n", (double) sum / count); + } else { + System.out.println("未读取到有效成绩"); + } + } catch (IOException e) { + + System.err.println("读取文件失败:" + e.getMessage()); + e.printStackTrace(); + } + } +}