diff --git a/w7/20.jpg b/w7/20.jpg new file mode 100644 index 0000000..51f4ba4 Binary files /dev/null and b/w7/20.jpg differ diff --git a/w7/35.jpg b/w7/35.jpg new file mode 100644 index 0000000..34b84d8 Binary files /dev/null and b/w7/35.jpg differ diff --git a/w7/ScoreCalculator.java b/w7/ScoreCalculator.java new file mode 100644 index 0000000..5155f79 --- /dev/null +++ b/w7/ScoreCalculator.java @@ -0,0 +1,71 @@ +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +public class ScoreCalculator { + + public static void main(String[] args) { + String fileName = "java/w7/ scores"; + double average = calculateAverageScore(fileName); + + if (!Double.isNaN(average)) { + System.out.printf("平均分: %.2f%n", average); + } + } + + /** + * 计算成绩文件的平均分 + * @param fileName 文件名 + * @return 平均分,如果出错返回 NaN + */ + public static double calculateAverageScore(String fileName) { + int sum = 0; + int count = 0; + + // 1. 检查文件是否存在 + Path filePath = Paths.get(fileName); + if (!Files.exists(filePath)) { + System.err.println("错误: 文件 '" + fileName + "' 不存在!"); + return Double.NaN; + } + + // 2. 使用 try-with-resources 确保流自动关闭 + try (BufferedReader br = new BufferedReader(new FileReader(fileName))) { + String line; + + while ((line = br.readLine()) != null) { + // 跳过空行 + if (line.trim().isEmpty()) { + continue; + } + + try { + int score = Integer.parseInt(line.trim()); + sum += score; + count++; + } catch (NumberFormatException e) { + // 数字格式错误,记录错误但继续处理其他行 + System.err.println("警告: 无效的数据格式 '" + line + "',已跳过此条记录"); + } + } + + // 检查是否有有效数据 + if (count == 0) { + System.err.println("错误: 文件中没有有效的成绩数据!"); + return Double.NaN; + } + + return (double) sum / count; + + } catch (IOException e) { + // 读取错误 + System.err.println("错误: 读取文件 '" + fileName + "' 时发生异常!"); + System.err.println("详细信息: " + e.getMessage()); + return Double.NaN; + } + // 无需显式 close(),try-with-resources 会自动处理 + } +} \ No newline at end of file diff --git a/w7/scores b/w7/scores new file mode 100644 index 0000000..35d93ee --- /dev/null +++ b/w7/scores @@ -0,0 +1,5 @@ +85 +90 +78 +92 +88 \ No newline at end of file