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.
45 lines
1.7 KiB
45 lines
1.7 KiB
import java.io.BufferedReader;
|
|
import java.io.FileReader;
|
|
import java.io.IOException;
|
|
|
|
public class ScoreTest {
|
|
public static void main(String[] args) {
|
|
// 定义文件路径
|
|
String fileName = "scores.txt";
|
|
|
|
// 初始化变量
|
|
int sum = 0; // 总分
|
|
int count = 0; // 人数(行数)
|
|
|
|
// 使用 try-with-resources 自动关闭流
|
|
// 即使发生异常,br 也会自动关闭
|
|
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
|
|
String line;
|
|
// 循环读取每一行
|
|
while ((line = br.readLine()) != null) {
|
|
try {
|
|
// 尝试将字符串转换为整数并累加
|
|
sum += Integer.parseInt(line);
|
|
count++;
|
|
} catch (NumberFormatException e) {
|
|
// 处理数字格式错误(例如文件中有空行或文字)
|
|
System.out.println("警告:发现无效数字格式 -> " + line + ",已跳过该行。");
|
|
}
|
|
}
|
|
|
|
// 计算并输出结果
|
|
if (count > 0) {
|
|
System.out.println("读取完成。");
|
|
System.out.println("总分: " + sum);
|
|
System.out.println("平均分: " + ((double) sum / count));
|
|
} else {
|
|
System.out.println("文件为空或没有有效数据。");
|
|
}
|
|
|
|
} catch (IOException e) {
|
|
// 处理文件找不到或读取错误
|
|
System.err.println("错误:无法读取文件 '" + fileName + "'。请确保文件存在且路径正确。");
|
|
e.printStackTrace();
|
|
}
|
|
}
|
|
}
|