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.

62 lines
2.0 KiB

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.File;
/**
* 成绩计算器 - 从文件读取成绩并计算平均分
*/
public class ScoreCalculator {
public static void main(String[] args) {
// 使用 w7 目录的绝对路径
String fileName = "D:\\Project\\java\\w7\\scores.txt";
// 如果命令行提供了参数,使用参数作为文件名
if (args.length > 0) {
fileName = args[0];
}
// 先检查文件是否存在
if (!Files.exists(Paths.get(fileName))) {
System.err.println("错误:文件 " + fileName + " 不存在!");
return;
}
int sum = 0;
int count = 0;
// 使用 try-with-resources 自动关闭资源
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null) {
line = line.trim(); // 去除首尾空格
if (line.isEmpty()) {
continue; // 跳过空行
}
try {
int score = Integer.parseInt(line);
sum += score;
count++;
} catch (NumberFormatException e) {
System.err.println("警告:无效的成绩格式 '" + line + "',已跳过该行");
}
}
} catch (IOException e) {
System.err.println("错误:读取文件时发生异常 - " + e.getMessage());
return;
}
// 计算并输出平均分
if (count > 0) {
double average = (double) sum / count;
System.out.println("共读取 " + count + " 个有效成绩");
System.out.println("总分:" + sum);
System.out.printf("平均分:%.2f%n", average);
} else {
System.out.println("未读取到任何有效成绩");
}
}
}