4 changed files with 69 additions and 0 deletions
Binary file not shown.
@ -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(); |
|||
} |
|||
} |
|||
} |
|||
@ -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 |
|||
|
After Width: | Height: | Size: 69 KiB |
Loading…
Reference in new issue