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.

56 lines
2.3 KiB

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ScoreCalculator {
public static void main(String[] args) {
// 定义文件路径
String fileName = "java/scores.txt";
// 初始化变量
int sum = 0; // 总分
int count = 0; // 有效分数的数量
System.out.println("开始读取文件: " + fileName);
// 1. 使用 try-with-resources 语法
// 这样无论是否发生异常,br (BufferedReader) 都会自动关闭,无需手动调用 br.close()
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
// 循环读取每一行
while ((line = br.readLine()) != null) {
try {
// 尝试将行内容转换为整数
int score = Integer.parseInt(line.trim()); // 使用 trim() 去除可能的空格
sum += score;
count++;
} catch (NumberFormatException e) {
// 2. 处理数字格式错误 (例如文件中包含 "abc")
System.err.println("警告:发现非数字内容 '" + line + "',已跳过该行。");
}
}
// 计算并输出平均分
if (count > 0) {
double average = (double) sum / count;
System.out.println("----------------------");
System.out.println("读取完成!");
System.out.println("总分数: " + sum);
System.out.println("有效条目数: " + count);
System.out.println("平均分: " + average);
} else {
System.out.println("文件中没有有效的数字数据。");
}
} catch (FileNotFoundException e) {
// 3. 处理文件不存在的情况
System.err.println("错误:找不到文件 '" + fileName + "'。请确保文件在项目根目录下。");
} catch (IOException e) {
// 4. 处理其他读取错误(如权限问题、磁盘损坏等)
System.err.println("错误:读取文件时发生 IO 异常:" + e.getMessage());
}
}
}