diff --git a/w7/AI协助记录.txt b/w7/AI协助记录.txt new file mode 100644 index 0000000..b91abbf --- /dev/null +++ b/w7/AI协助记录.txt @@ -0,0 +1,3 @@ +1.借助AI复习异常处理相关知识点 +2.借助AI了解BufferReader是带缓冲区的高效文件读取器,按行读取文本,FileReader是打开本地txt文件的基础字符流,在使用之前需要import +3.让AI帮忙修改润色代码,了解到try-with-resource不需要手写br.close();不需要添加final。 \ No newline at end of file diff --git a/w7/BeforeTry.java b/w7/BeforeTry.java new file mode 100644 index 0000000..4002c4c --- /dev/null +++ b/w7/BeforeTry.java @@ -0,0 +1,19 @@ +import java.io.BufferedReader; +import java.io.FileReader; + + +public class Try { + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new FileReader("scores.txt")); + String line; + int sum = 0; + int count = 0; + while ((line = br.readLine()) != null) { + sum += Integer.parseInt(line); + count++; + } + System.out.println("总分:" + sum); + System.out.println("平均分:" + (sum * 1.0 / count)); + br.close(); + } +} \ No newline at end of file diff --git a/w7/Try.java b/w7/Try.java new file mode 100644 index 0000000..e94883d --- /dev/null +++ b/w7/Try.java @@ -0,0 +1,36 @@ +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.FileNotFoundException; +import java.io.IOException; + +public class Try { + public static void main(String[] args) { + int sum = 0; + int count = 0; + + try (BufferedReader br = new BufferedReader(new FileReader("scores.txt"))) { + String line; + while ((line = br.readLine()) != null) { + try { + sum += Integer.parseInt(line); + count++; + } catch (NumberFormatException e) { + System.out.println("警告:第" + (count + 1) + "行不是有效的数字: " + line); + } + } + + if (count > 0) { + System.out.println("总分:" + sum); + System.out.println("平均分:" + (sum * 1.0 / count)); + } else { + System.out.println("没有有效的成绩数据"); + } + } catch (FileNotFoundException e) { + System.out.println("错误:文件不存在或无法访问: " + e.getMessage()); + } catch (IOException e) { + System.out.println("错误:文件读取失败: " + e.getMessage()); + } catch (Exception e) { + System.out.println("错误:发生未知错误: " + e.getMessage()); + } + } +} \ No newline at end of file diff --git a/w7/无异常处理.png b/w7/无异常处理.png new file mode 100644 index 0000000..3cf0fe4 Binary files /dev/null and b/w7/无异常处理.png differ diff --git a/w7/添加异常处理.png b/w7/添加异常处理.png new file mode 100644 index 0000000..7f2debd Binary files /dev/null and b/w7/添加异常处理.png differ