diff --git a/w7/ScoreCalculator.java b/w7/ScoreCalculator.java new file mode 100644 index 0000000..c8e3ba5 --- /dev/null +++ b/w7/ScoreCalculator.java @@ -0,0 +1,33 @@ +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; + +public class ScoreCalculator { + public static void main(String[] args) { + String fileName = "scores.txt"; + int sum = 0; + int count = 0; + try (BufferedReader br = new BufferedReader(new FileReader(fileName))) { + String line; + while ((line = br.readLine()) != null) { + try { + int score = Integer.parseInt(line.trim()); + sum += score; + count++; + } catch (NumberFormatException e) { + System.err.println("警告:文件中包含无效数字,跳过该行:" + line); + } + } + if (count > 0) { + double average = (double) sum / count; + System.out.println("平均分:" + average); + } else { + System.out.println("文件中没有有效成绩数据"); + } + + } catch (IOException e) { + System.err.println("文件读取错误:" + e.getMessage()); + } + } +} +