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.
 
 

49 lines
1.7 KiB

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ScoreAverageCalculator {
public static void main(String[] args) {
String fileName = "scores.txt";
int sum = 0;
int count = 0;
// 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) {
double average = (double) sum / count;
System.out.println("成功读取 " + count + " 个成绩");
System.out.println("总分: " + sum);
System.out.println("平均分: " + average);
} else {
System.err.println("文件中没有有效的成绩数据");
}
} catch (IOException e) {
// 文件不存在或读取错误处理
System.err.println("文件操作错误: " + e.getMessage());
if (e instanceof java.io.FileNotFoundException) {
System.err.println("请检查文件 \"" + fileName + "\" 是否存在");
}
}
}
}