diff --git a/w7/ScoreCalculator.class b/w7/ScoreCalculator.class new file mode 100644 index 0000000..9c6075b Binary files /dev/null and b/w7/ScoreCalculator.class differ diff --git a/w7/ScoreCalculator.java b/w7/ScoreCalculator.java new file mode 100644 index 0000000..1f2a1e4 --- /dev/null +++ b/w7/ScoreCalculator.java @@ -0,0 +1,44 @@ +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"; + calculateAverage(fileName); + } + + public static void calculateAverage(String fileName) { + int sum = 0; + int count = 0; + + // 使用try-with-resources确保流被关闭 + try (BufferedReader br = new BufferedReader(new FileReader(fileName))) { + String line; + while ((line = br.readLine()) != null) { + try { + // 尝试解析数字 + int score = Integer.parseInt(line); + sum += score; + count++; + } catch (NumberFormatException e) { + System.out.println("警告: 无法解析行 '" + line + "' 为数字,跳过该行"); + } + } + + // 计算平均分 + if (count > 0) { + double average = (double) sum / count; + System.out.println("总分: " + sum); + System.out.println("总人数: " + count); + System.out.println("平均分: " + average); + } else { + System.out.println("没有有效的分数数据"); + } + + } catch (IOException e) { + System.out.println("错误: 无法读取文件 '" + fileName + "'"); + System.out.println("原因: " + e.getMessage()); + } + } +} \ No newline at end of file diff --git a/w7/scores.txt b/w7/scores.txt new file mode 100644 index 0000000..32bf3e3 --- /dev/null +++ b/w7/scores.txt @@ -0,0 +1,5 @@ +85 +90 +78 +92 +88 \ No newline at end of file