Browse Source

宋瑞-202506050301

main
Songrui 3 weeks ago
parent
commit
9ca5d18f94
  1. 56
      w7/ReadMe.md
  2. 62
      w7/ScoreCalculator.java
  3. 5
      w7/scores.txt

56
w7/ReadMe.md

@ -0,0 +1,56 @@
AI 交互记录 - Java 代码重构
任务背景
重构"裸奔"的 Java 代码,实现从 scores.txt 读取成绩并计算平均分的功能。
交互过程
第1轮:初始需求
原始代码
BufferedReader br = new BufferedReader(new FileReader("scores.txt"));
String line;
while ((line = br.readLine()) != null) {
sum += Integer.parseInt(line);
}
br.close();
重构要求:
添加完整的异常处理(文件不存在、读取错误、数字格式错误)
强制使用 try-with-resources 语法
第2轮:文件创建与初步指导
AI 回复要点:
建议在 D:\Project\java\练习 目录创建 ScoreCalculator.java
提供完整代码,包含三层异常处理
说明编译运行步骤
关键代码片段:
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
// 读取逻辑
} catch (IOException e) {
// 异常处理
}
技术要点总结
核心改进
资源管理:手动关闭 → try-with-resources 自动关闭
异常处理:无处理 → 三层捕获(文件存在性、IO、格式)
健壮性:空行处理、trim、动态计数
精度提升:整数除法 → double 类型保留2位小数
遇到的问题
❌ 相对路径导致文件找不到
❌ getResource() 在 Windows 下路径格式错误
✅ 最终使用绝对路径解决
最终代码特性
✓ 完整的异常处理机制
✓ 自动资源管理
✓ 支持命令行参数覆盖
✓ 友好的错误提示
✓ 精确的平均分计算
测试数据
scores.txt 内容:
85
90
78
abc
92
预期输出:
警告:无效的成绩格式 'abc',已跳过该行
共读取 4 个有效成绩
总分:345
平均分:86.25

62
w7/ScoreCalculator.java

@ -0,0 +1,62 @@
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.File;
/**
* 成绩计算器 - 从文件读取成绩并计算平均分
*/
public class ScoreCalculator {
public static void main(String[] args) {
// 使用 w7 目录的绝对路径
String fileName = "D:\\Project\\java\\w7\\scores.txt";
// 如果命令行提供了参数,使用参数作为文件名
if (args.length > 0) {
fileName = args[0];
}
// 先检查文件是否存在
if (!Files.exists(Paths.get(fileName))) {
System.err.println("错误:文件 " + fileName + " 不存在!");
return;
}
int sum = 0;
int count = 0;
// 使用 try-with-resources 自动关闭资源
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null) {
line = line.trim(); // 去除首尾空格
if (line.isEmpty()) {
continue; // 跳过空行
}
try {
int score = Integer.parseInt(line);
sum += score;
count++;
} catch (NumberFormatException e) {
System.err.println("警告:无效的成绩格式 '" + line + "',已跳过该行");
}
}
} catch (IOException e) {
System.err.println("错误:读取文件时发生异常 - " + e.getMessage());
return;
}
// 计算并输出平均分
if (count > 0) {
double average = (double) sum / count;
System.out.println("共读取 " + count + " 个有效成绩");
System.out.println("总分:" + sum);
System.out.printf("平均分:%.2f%n", average);
} else {
System.out.println("未读取到任何有效成绩");
}
}
}

5
w7/scores.txt

@ -0,0 +1,5 @@
85
90
78
abc
92
Loading…
Cancel
Save