Browse Source

202506050218

main
wangminjun 2 months ago
parent
commit
010bfb3a48
  1. 3
      w7/AI协助记录.txt
  2. 19
      w7/BeforeTry.java
  3. 36
      w7/Try.java
  4. BIN
      w7/无异常处理.png
  5. BIN
      w7/添加异常处理.png

3
w7/AI协助记录.txt

@ -0,0 +1,3 @@
1.借助AI复习异常处理相关知识点
2.借助AI了解BufferReader是带缓冲区的高效文件读取器,按行读取文本,FileReader是打开本地txt文件的基础字符流,在使用之前需要import
3.让AI帮忙修改润色代码,了解到try-with-resource不需要手写br.close();不需要添加final。

19
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();
}
}

36
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());
}
}
}

BIN
w7/无异常处理.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 348 KiB

BIN
w7/添加异常处理.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 374 KiB

Loading…
Cancel
Save