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.
58 lines
2.3 KiB
58 lines
2.3 KiB
package w7;
|
|
|
|
import java.io.BufferedReader;
|
|
import java.io.FileReader;
|
|
import java.io.IOException;
|
|
|
|
public class ScoreAverage {
|
|
public static void main(String[] args) {
|
|
// 1. 定义变量:总分、人数、平均分
|
|
int sum = 0;
|
|
int count = 0;
|
|
double average = 0.0;
|
|
|
|
// 2. 使用 try-with-resources 自动关闭 BufferedReader
|
|
// 这样不管有没有异常,流都会被关闭,不用手动写 br.close()
|
|
try (BufferedReader br = new BufferedReader(new FileReader("scores.txt"))) {
|
|
String line;
|
|
|
|
// 3. 逐行读取文件
|
|
while ((line = br.readLine()) != null) {
|
|
// 去掉每行前后的空格,避免空行或空格导致的问题
|
|
line = line.trim();
|
|
|
|
// 跳过空行(防止文件里有空行报错)
|
|
if (line.isEmpty()) {
|
|
continue;
|
|
}
|
|
|
|
// 4. 把字符串转为整数成绩
|
|
int score = Integer.parseInt(line);
|
|
sum += score;
|
|
count++;
|
|
}
|
|
|
|
// 5. 计算平均分(要先判断人数不为0,避免除以0)
|
|
if (count > 0) {
|
|
average = (double) sum / count;
|
|
System.out.println("总分:" + sum);
|
|
System.out.println("人数:" + count);
|
|
System.out.println("平均分:" + average);
|
|
} else {
|
|
System.out.println("文件里没有有效成绩数据");
|
|
}
|
|
|
|
} catch (java.io.FileNotFoundException e) {
|
|
// 异常1:文件不存在
|
|
System.out.println("错误:找不到文件 scores.txt,请检查文件是否存在!");
|
|
} catch (IOException e) {
|
|
// 异常2:读取文件时出错(比如文件被占用、读取失败)
|
|
System.out.println("错误:读取文件时发生异常!");
|
|
e.printStackTrace(); // 打印详细错误信息,方便排查
|
|
} catch (NumberFormatException e) {
|
|
// 异常3:数字格式错误(比如文件里有字母、符号,转不成整数)
|
|
System.out.println("错误:文件中有非数字内容,无法转换为成绩!");
|
|
e.printStackTrace();
|
|
}
|
|
}
|
|
}
|
|
|