2 changed files with 51 additions and 0 deletions
@ -0,0 +1 @@ |
|||
本次我请教了 Java 成绩文件读取裸奔代码的重构问题,不清楚如何完善文件 IO 异常处理、规范安全关闭文件流。AI 帮我梳理了文件不存在、读取异常、数字格式错误三类报错场景,指导我用 try-with-resources 写法自动释放 IO 资源,补全分层异常捕获逻辑。同时优化了代码容错处理,完善平均分计算逻辑,对比讲解了重构前后代码差异,帮我快速写出规范完整、可正常运行的作业代码,弄懂了 Java 文件流异常处理与资源安全管理的相关知识点。 |
|||
@ -0,0 +1,50 @@ |
|||
import java.io.BufferedReader; |
|||
import java.io.FileReader; |
|||
import java.io.IOException; |
|||
|
|||
/** |
|||
* 读取scores.txt文件计算平均分 |
|||
* 包含完整异常处理与资源自动关闭 |
|||
*/ |
|||
public class ScoreAverage { |
|||
public static void main(String[] args) { |
|||
// 初始化总和与计数
|
|||
int sum = 0; |
|||
int count = 0; |
|||
|
|||
// try-with-resources 自动关闭流,无需手动调用 close()
|
|||
try (BufferedReader br = new BufferedReader(new FileReader("scores.txt"))) { |
|||
String line; |
|||
// 逐行读取文件
|
|||
while ((line = br.readLine()) != null) { |
|||
// 去除行首尾空白(避免空行/空格干扰)
|
|||
line = line.trim(); |
|||
// 跳过空行
|
|||
if (line.isEmpty()) { |
|||
continue; |
|||
} |
|||
// 数字格式转换与累加
|
|||
sum += Integer.parseInt(line); |
|||
count++; |
|||
} |
|||
|
|||
// 计算并输出平均分(处理无数据情况)
|
|||
if (count > 0) { |
|||
double average = (double) sum / count; |
|||
System.out.printf("总分:%d,人数:%d,平均分:%.2f%n", sum, count, average); |
|||
} else { |
|||
System.out.println("文件中无有效成绩数据"); |
|||
} |
|||
|
|||
} catch (java.io.FileNotFoundException e) { |
|||
// 捕获:文件不存在/无法读取
|
|||
System.out.println("错误:文件未找到 - " + e.getMessage()); |
|||
} catch (NumberFormatException e) { |
|||
// 捕获:行内容非有效整数
|
|||
System.out.println("错误:数据格式非有效整数 - " + e.getMessage()); |
|||
} catch (IOException e) { |
|||
// 捕获:读取文件时的IO异常
|
|||
System.out.println("错误:读取文件失败 - " + e.getMessage()); |
|||
} |
|||
} |
|||
} |
|||
Loading…
Reference in new issue