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.

38 lines
1.4 KiB

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ScoreCalculator {
public static void main(String[] args) {
String filePath = "scores.txt";
int sum = 0;
int count = 0;
// try-with-resources 自动关闭流,无需手动 close()
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
try {
// 处理数字格式错误
int score = Integer.parseInt(line.trim());
sum += score;
count++;
} catch (NumberFormatException e) {
System.err.println("警告:无法解析分数 '" + line + "',跳过该数据。");
}
}
if (count > 0) {
double average = (double) sum / count;
System.out.printf("平均分:%.2f%n", average);
} else {
System.out.println("文件中没有有效分数数据。");
}
} catch (java.io.FileNotFoundException e) {
System.err.println("错误:文件不存在,请检查路径 '" + filePath + "'。");
} catch (IOException e) {
System.err.println("错误:读取文件失败 - " + e.getMessage());
}
}
}