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.
 
 
 

71 lines
2.3 KiB

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class ScoreCalculator {
public static void main(String[] args) {
String fileName = "java/w7/ scores";
double average = calculateAverageScore(fileName);
if (!Double.isNaN(average)) {
System.out.printf("平均分: %.2f%n", average);
}
}
/**
* 计算成绩文件的平均分
* @param fileName 文件名
* @return 平均分,如果出错返回 NaN
*/
public static double calculateAverageScore(String fileName) {
int sum = 0;
int count = 0;
// 1. 检查文件是否存在
Path filePath = Paths.get(fileName);
if (!Files.exists(filePath)) {
System.err.println("错误: 文件 '" + fileName + "' 不存在!");
return Double.NaN;
}
// 2. 使用 try-with-resources 确保流自动关闭
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null) {
// 跳过空行
if (line.trim().isEmpty()) {
continue;
}
try {
int score = Integer.parseInt(line.trim());
sum += score;
count++;
} catch (NumberFormatException e) {
// 数字格式错误,记录错误但继续处理其他行
System.err.println("警告: 无效的数据格式 '" + line + "',已跳过此条记录");
}
}
// 检查是否有有效数据
if (count == 0) {
System.err.println("错误: 文件中没有有效的成绩数据!");
return Double.NaN;
}
return (double) sum / count;
} catch (IOException e) {
// 读取错误
System.err.println("错误: 读取文件 '" + fileName + "' 时发生异常!");
System.err.println("详细信息: " + e.getMessage());
return Double.NaN;
}
// 无需显式 close(),try-with-resources 会自动处理
}
}