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.2 KiB

package org.example;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ScoreReader {
public static void main(String[] args) {
int sum = 0;
int count = 0;
// try-with-resources:自动关闭流,不需要手动 br.close()
try (BufferedReader br = new BufferedReader(new FileReader("scores.txt"))) {
String line;
while ((line = br.readLine()) != null) {
try {
sum += Integer.parseInt(line.trim());
count++;
} catch (NumberFormatException e) {
// 处理数字格式错误
System.out.println("跳过无效数据:" + line);
}
}
if (count > 0) {
double average = (double) sum / count;
System.out.println("总分:" + sum);
System.out.println("人数:" + count);
System.out.printf("平均分:%.2f%n", average);
} else {
System.out.println("文件中没有有效成绩。");
}
} catch (FileNotFoundException e) {
// 处理文件不存在
System.out.println("错误:找不到文件 scores.txt,请检查路径。");
} catch (IOException e) {
// 处理读取错误
System.out.println("错误:读取文件时发生异常:" + e.getMessage());
}
}
}