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.

41 lines
1.6 KiB

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileNotFoundException;
public class ScoreCalculator {
public static void main(String[] args) {
String filePath = "scores.txt";
int sum = 0;
int count = 0;
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.out.println("警告:跳过无效的数字格式 - \"" + line + "\"");
}
}
if (count == 0) {
System.out.println("未找到有效的成绩数据");
} else {
double average = (double) sum / count;
System.out.println("========== 成绩统计结果 ==========");
System.out.println("有效成绩数量: " + count);
System.out.println("总成绩: " + sum);
System.out.println("平均分: " + String.format("%.2f", average));
}
} catch (FileNotFoundException e) {
System.out.println("错误:文件不存在 - " + filePath);
System.out.println("请确保 scores.txt 文件位于程序运行目录下");
} catch (IOException e) {
System.out.println("错误:文件读取失败 - " + e.getMessage());
}
}
}