diff --git a/W7/AI协助说明.txt b/W7/AI协助说明.txt new file mode 100644 index 0000000..63b37af --- /dev/null +++ b/W7/AI协助说明.txt @@ -0,0 +1,45 @@ +使用豆包与通义灵码; + +代码说明 +1.try-with-resources:BufferedReader 会在 try 代码块结束后自动关闭,不用手动写 br.close(),更安全。 +2.双重异常处理: +外层 catch (IOException e):处理文件不存在、读取出错的情况。 +内层 catch (NumberFormatException e):处理文件里有非数字内容的情况(比如不小心写了字母),不会让整个程序崩溃。 + + +1.什么是try-with-resource? +区别:只是在 try 后面的括号 () 中声明了资源。 +eg. try (BufferedReader reader = new BufferedReader(new FileReader("score.txt"))) { +优点:会自动关闭文件 + +2.为什么reader会报错? +变量作用域规则:在 try(...) 括号内声明的变量,只能在 try-catch 块内部使用。 +try (BufferedReader reader = ...) { ← reader 从这里开始存在 + // reader 可以使用 ✅ +} catch (IOException e) { + // reader 可以使用 ✅ +} ← reader 在这里被自动关闭并销毁 + +reader.close(); ← reader 已经不存在了 ❌ + +3.创建的Scores.txt文件应该放在哪里? + +代码里写的 new FileReader("scores.txt"),是相对路径,它的默认查找位置是: +项目编译后,class 文件运行的根目录 +对于你的项目结构来说,就是 Test/out/production/Test 这个目录 +如果把文件放在 src/W7/ 里,运行时就找不到了,因为程序会在根目录找,而不是在 W7 包里找。 + +4.. 为什么 “裸奔版” 代码里这么写会有问题? +没有异常处理:如果文件不存在、读取出错,程序会直接崩溃。 +没有自动关闭流:如果程序中途出错,br.close() 可能执行不到,会导致文件资源泄漏。 +没有数字格式校验:如果文件里有非数字内容,Integer.parseInt(line) 会直接报错。 + +5.裸奔代码每一行表示的意义 +代码行 核心作用 问题 +BufferedReader br = ... 打开 scores.txt 并创建带缓冲的读取器 无异常处理,文件不存在直接崩溃 +String line; 声明变量存每行内容 无问题,但无实际防护 +while ((line = br.readLine()) != null) 循环读取文件每一行 无异常处理,读取失败直接崩溃 +sum += Integer.parseInt(line); 转数字并累加总分 无格式校验,非数字内容直接崩溃 +br.close(); 关闭文件释放资源 中途报错则执行不到,导致资源泄漏 + + diff --git a/W7/Scores.txt b/W7/Scores.txt new file mode 100644 index 0000000..7307d15 --- /dev/null +++ b/W7/Scores.txt @@ -0,0 +1,28 @@ +package W7; + +import java.io.BufferedReader; // 导入带缓冲的文本读取类 +import java.io.FileReader; // 导入文件读取类 +import java.io.IOException; // 导入IO异常类(处理文件读取错误) + +public class Scores { + public static void main(String[] args) { + int sum = 0; + try (BufferedReader reader = new BufferedReader(new FileReader("score.txt"))) { + String line; + while ((line = reader.readLine()) != null) { + try { + // 正常步骤:把读到的字符串转成数字 + int score = Integer.parseInt(line.trim()); + // 正常步骤:分数加起来 + sum += score; + } catch (NumberFormatException e) { + // 错误步骤:把异常信息打印出来 + System.out.println("数字格式错误: " + line); + } + } + } catch (IOException e) { + System.out.println("文件读取错误: " + e.getMessage()); + } + System.out.println("总分是:" + sum); + } +} diff --git a/W7/数字格式错误.png b/W7/数字格式错误.png new file mode 100644 index 0000000..0cc64bc Binary files /dev/null and b/W7/数字格式错误.png differ diff --git a/W7/文件读取错误.png b/W7/文件读取错误.png new file mode 100644 index 0000000..63c852f Binary files /dev/null and b/W7/文件读取错误.png differ