Browse Source

上传文件至 'w7'

main
XuJiexian 2 months ago
parent
commit
5ac5f70e7c
  1. BIN
      w7/SafeScoreAvg.class
  2. 45
      w7/SafeScoreAvg.java
  3. 24
      w7/scores.txt
  4. BIN
      w7/屏幕截图 2026-04-27 112423.png

BIN
w7/SafeScoreAvg.class

Binary file not shown.

45
w7/SafeScoreAvg.java

@ -0,0 +1,45 @@
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class SafeScoreAvg {
public static void main(String[] args) {
String filePath = "scores.txt";
int sum = 0;
int count = 0;
// 1. 使用 try-with-resources,自动关闭流
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
// 去掉前后空格,跳过空行
line = line.trim();
if (line.isEmpty()) {
continue;
}
// 2. 处理数字格式错误
try {
int score = Integer.parseInt(line);
sum += score;
count++;
} catch (NumberFormatException e) {
System.err.println("⚠️ 警告:跳过无效成绩行(非数字内容):" + line);
}
}
// 计算并输出结果
if (count == 0) {
System.out.println("ℹ️ 提示:文件中没有有效成绩数据");
} else {
double average = (double) sum / count;
System.out.printf("✅ 平均分:%.2f%n", average);
}
} catch (IOException e) {
// 3. 处理文件不存在、读取错误等IO异常
System.err.println("❌ 文件操作失败:" + e.getMessage());
e.printStackTrace();
}
}
}

24
w7/scores.txt

@ -0,0 +1,24 @@
85
92
78
95
88
75
90
82
96
89
70
88
abc
93
79
84
91
缺考
87
76
99
81
94

BIN
w7/屏幕截图 2026-04-27 112423.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

Loading…
Cancel
Save