You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
47 lines
2.0 KiB
47 lines
2.0 KiB
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("没有有效的分数记录,无法计算平均分~");
|
|
}
|
|
}
|
|
}
|
|
|