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.
44 lines
1.5 KiB
44 lines
1.5 KiB
import java.io.BufferedReader;
|
|
import java.io.FileReader;
|
|
import java.io.IOException;
|
|
|
|
public class ScoreCalculator {
|
|
public static void main(String[] args) {
|
|
String fileName = "scores.txt";
|
|
calculateAverage(fileName);
|
|
}
|
|
|
|
public static void calculateAverage(String fileName) {
|
|
int sum = 0;
|
|
int count = 0;
|
|
|
|
// 使用try-with-resources确保流被关闭
|
|
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
|
|
String line;
|
|
while ((line = br.readLine()) != null) {
|
|
try {
|
|
// 尝试解析数字
|
|
int score = Integer.parseInt(line);
|
|
sum += score;
|
|
count++;
|
|
} catch (NumberFormatException e) {
|
|
System.out.println("警告: 无法解析行 '" + line + "' 为数字,跳过该行");
|
|
}
|
|
}
|
|
|
|
// 计算平均分
|
|
if (count > 0) {
|
|
double average = (double) sum / count;
|
|
System.out.println("总分: " + sum);
|
|
System.out.println("总人数: " + count);
|
|
System.out.println("平均分: " + average);
|
|
} else {
|
|
System.out.println("没有有效的分数数据");
|
|
}
|
|
|
|
} catch (IOException e) {
|
|
System.out.println("错误: 无法读取文件 '" + fileName + "'");
|
|
System.out.println("原因: " + e.getMessage());
|
|
}
|
|
}
|
|
}
|