4 changed files with 65 additions and 0 deletions
@ -0,0 +1,18 @@ |
|||
package w7; |
|||
import java.io.BufferedReader; |
|||
import java.io.FileReader; |
|||
|
|||
public class RawCode { |
|||
public static void main(String[] args) { |
|||
int sum = 0; |
|||
// 1. 资源未自动关闭(若中间抛异常,br.close()不会执行)
|
|||
BufferedReader br = new BufferedReader(new FileReader("scores.txt")); |
|||
String line; |
|||
while ((line = br.readLine()) != null) { |
|||
// 2. 无数字格式异常处理(若行不是整数,直接崩溃)
|
|||
sum += Integer.parseInt(line); |
|||
} |
|||
// 3. 无IO异常处理(文件不存在/读取错误时直接崩溃)
|
|||
br.close(); |
|||
} |
|||
} |
|||
@ -0,0 +1,47 @@ |
|||
package w7; |
|||
import java.io.BufferedReader; |
|||
import java.io.FileReader; |
|||
import java.io.IOException; |
|||
import java.io.FileNotFoundException; |
|||
public class yichang { |
|||
public static void main(String[] args) { |
|||
int sum = 0; |
|||
int validCount = 0; // 记录有效分数的数量(避免除以0)
|
|||
|
|||
// 🔵 核心改进1:try-with-resources 自动关闭资源
|
|||
try (BufferedReader br = new BufferedReader(new FileReader("scores.txt"))) { |
|||
String line; |
|||
int lineNumber = 0; // 记录当前行号(用于错误提示)
|
|||
|
|||
while ((line = br.readLine()) != null) { |
|||
lineNumber++; |
|||
try { |
|||
// 尝试将行内容转为整数(处理数字格式错误)
|
|||
int score = Integer.parseInt(line); |
|||
sum += score; |
|||
validCount++; |
|||
} catch (NumberFormatException e) { |
|||
// 🔵 核心改进2:处理“数字格式错误”
|
|||
System.err.printf("第%d行的分数格式无效:%s%n", lineNumber, line); |
|||
} |
|||
} |
|||
|
|||
} catch (FileNotFoundException e) { |
|||
// 🔵 核心改进2:处理“文件不存在”
|
|||
System.err.println("错误:成绩文件 scores.txt 不存在!请检查路径~"); |
|||
e.printStackTrace(); // 打印堆栈跟踪,辅助调试
|
|||
} catch (IOException e) { |
|||
// 🔵 核心改进2:处理“读取IO错误”(如权限不足、磁盘故障等)
|
|||
System.err.println("错误:读取成绩文件时发生IO异常!"); |
|||
e.printStackTrace(); |
|||
} |
|||
|
|||
// 输出平均分(仅当有有效数据时计算)
|
|||
if (validCount > 0) { |
|||
double average = (double) sum / validCount; |
|||
System.out.printf("成绩的平均分是:%.2f%n", average); |
|||
} else { |
|||
System.out.println("没有有效的分数记录,无法计算平均分~"); |
|||
} |
|||
} |
|||
} |
|||
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 134 KiB |
Loading…
Reference in new issue