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.

36 lines
1.1 KiB

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ScoreAverage {
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) {
line = line.trim();
if (line.isEmpty()) continue;
try {
sum += Integer.parseInt(line);
count++;
} catch (NumberFormatException e) {
System.err.println("无效成绩:" + line);
}
}
if (count > 0) {
double avg = (double) sum / count;
System.out.println("平均分:" + avg);
} else {
System.out.println("无有效成绩数据");
}
} catch (IOException e) {
System.err.println("文件读取失败:" + e.getMessage());
}
}
}