5 changed files with 58 additions and 0 deletions
@ -0,0 +1,3 @@ |
|||
1.借助AI复习异常处理相关知识点 |
|||
2.借助AI了解BufferReader是带缓冲区的高效文件读取器,按行读取文本,FileReader是打开本地txt文件的基础字符流,在使用之前需要import |
|||
3.让AI帮忙修改润色代码,了解到try-with-resource不需要手写br.close();不需要添加final。 |
|||
@ -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(); |
|||
} |
|||
} |
|||
@ -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()); |
|||
} |
|||
} |
|||
} |
|||
|
After Width: | Height: | Size: 348 KiB |
|
After Width: | Height: | Size: 374 KiB |
Loading…
Reference in new issue