diff --git a/ScoreAverage.class b/ScoreAverage.class new file mode 100644 index 0000000..7cada3c Binary files /dev/null and b/ScoreAverage.class differ diff --git a/ScoreAverage.java b/ScoreAverage.java new file mode 100644 index 0000000..f99c1b3 --- /dev/null +++ b/ScoreAverage.java @@ -0,0 +1,52 @@ +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; + +public class ScoreAverage { + public static void main(String[] args) { + // 1. 定义变量:总分、有效成绩数量 + int sum = 0; + int count = 0; + + // 2. 使用 try-with-resources 自动关闭流,确保文件一定被关闭 + try (BufferedReader br = new BufferedReader(new FileReader("scores.txt"))) { + String line; + while ((line = br.readLine()) != null) { + // 去除首尾空格,避免空行或空格干扰 + line = line.trim(); + if (line.isEmpty()) { + continue; // 跳过空行 + } + + // 3. 解析数字并累加 + int score = Integer.parseInt(line); + sum += score; + count++; + } + + // 4. 计算并输出平均分(避免除以0) + if (count > 0) { + double average = (double) sum / count; + System.out.println("读取到 " + count + " 个成绩"); + System.out.printf("总分:%d,平均分:%.2f%n", sum, average); + } else { + System.out.println("文件中没有有效成绩数据"); + } + + // 异常1:文件不存在/路径错误 + } catch (IOException e) { + System.out.println("文件读取错误:" + e.getMessage()); + System.out.println("请检查 scores.txt 文件是否存在,或路径是否正确"); + + // 异常2:数字格式错误(比如文件里有非数字内容) + } catch (NumberFormatException e) { + System.out.println("数据格式错误:文件中包含无法解析为整数的内容"); + System.out.println("错误详情:" + e.getMessage()); + + // 兜底异常,捕获其他意外错误 + } catch (Exception e) { + System.out.println("程序发生意外错误:" + e.getMessage()); + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/scores.txt b/scores.txt new file mode 100644 index 0000000..6d371a5 --- /dev/null +++ b/scores.txt @@ -0,0 +1,5 @@ +85 +92 +78 +90 +88 \ No newline at end of file