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.
83 lines
3.0 KiB
83 lines
3.0 KiB
import java.io.*;
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
|
|
// =============== 自定义异常类(面向对象体现) ===============
|
|
class InvalidScoreException extends Exception {
|
|
public InvalidScoreException(String message) {
|
|
super(message);
|
|
}
|
|
}
|
|
|
|
// =============== 成绩处理器类 ===============
|
|
class ScoreProcessor {
|
|
private List<Integer> scores = new ArrayList<>();
|
|
|
|
/**
|
|
* 从指定文件读取成绩
|
|
* @param filename 文件名
|
|
* @throws IOException 文件读取错误
|
|
* @throws InvalidScoreException 成绩格式无效
|
|
*/
|
|
public void loadScoresFromFile(String filename) throws IOException, InvalidScoreException {
|
|
scores.clear();
|
|
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
|
|
String line;
|
|
int lineNumber = 0;
|
|
while ((line = reader.readLine()) != null) {
|
|
lineNumber++;
|
|
line = line.trim();
|
|
if (line.isEmpty()) continue; // 跳过空行
|
|
|
|
try {
|
|
int score = Integer.parseInt(line);
|
|
if (score < 0 || score > 100) {
|
|
throw new InvalidScoreException("第 " + lineNumber + " 行:成绩应在 0~100 之间,但得到 " + score);
|
|
}
|
|
scores.add(score);
|
|
} catch (NumberFormatException e) {
|
|
throw new InvalidScoreException("第 " + lineNumber + " 行:\"" + line + "\" 不是有效的整数");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 计算平均分
|
|
* @return 平均分(保留两位小数)
|
|
* @throws IllegalStateException 如果没有有效成绩
|
|
*/
|
|
public double calculateAverage() {
|
|
if (scores.isEmpty()) {
|
|
throw new IllegalStateException("没有可计算的有效成绩");
|
|
}
|
|
int sum = scores.stream().mapToInt(Integer::intValue).sum();
|
|
return Math.round((double) sum / scores.size() * 100) / 100.0;
|
|
}
|
|
|
|
public int getScoreCount() {
|
|
return scores.size();
|
|
}
|
|
}
|
|
|
|
// =============== 主类 ===============
|
|
public class Main {
|
|
public static void main(String[] args) {
|
|
ScoreProcessor processor = new ScoreProcessor();
|
|
|
|
try {
|
|
processor.loadScoresFromFile("scores.txt");
|
|
double average = processor.calculateAverage();
|
|
System.out.printf("共读取 %d 条有效成绩,平均分:%.2f%n",
|
|
processor.getScoreCount(), average);
|
|
} catch (FileNotFoundException e) {
|
|
System.err.println("❌ 文件未找到:请确保 'scores.txt' 存在于当前目录。");
|
|
} catch (IOException e) {
|
|
System.err.println("❌ 读取文件时发生 I/O 错误:" + e.getMessage());
|
|
} catch (InvalidScoreException e) {
|
|
System.err.println("❌ 成绩数据格式错误:" + e.getMessage());
|
|
} catch (IllegalStateException e) {
|
|
System.err.println("❌ 数据不足:" + e.getMessage());
|
|
}
|
|
}
|
|
}
|