5 changed files with 62 additions and 0 deletions
@ -0,0 +1,44 @@ |
|||||
|
import java.io.BufferedReader; |
||||
|
import java.io.FileReader; |
||||
|
import java.io.IOException; |
||||
|
|
||||
|
public class ScoreAverage { |
||||
|
public static void main(String[] args) { |
||||
|
String fileName = "scores.txt"; |
||||
|
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); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// 计算并输出平均分
|
||||
|
if (count > 0) { |
||||
|
double average = (double) sum / count; |
||||
|
System.out.printf("总分:%d,有效成绩数:%d,平均分:%.2f%n", sum, count, average); |
||||
|
} else { |
||||
|
System.out.println("文件中没有有效的成绩数据。"); |
||||
|
} |
||||
|
|
||||
|
} catch (IOException e) { |
||||
|
// 处理文件不存在、读取错误等IO异常
|
||||
|
System.err.println("文件操作出错:" + e.getMessage()); |
||||
|
e.printStackTrace(); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,11 @@ |
|||||
|
<?xml version="1.0" encoding="UTF-8"?> |
||||
|
<module type="JAVA_MODULE" version="4"> |
||||
|
<component name="NewModuleRootManager" inherit-compiler-output="true"> |
||||
|
<exclude-output /> |
||||
|
<content url="file://$MODULE_DIR$"> |
||||
|
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" /> |
||||
|
</content> |
||||
|
<orderEntry type="inheritedJdk" /> |
||||
|
<orderEntry type="sourceFolder" forTests="false" /> |
||||
|
</component> |
||||
|
</module> |
||||
@ -0,0 +1,2 @@ |
|||||
|
[LocalizedFileNames] |
||||
|
ÆÁÄ»½ØÍ¼ 2026-04-19 235510.png=@ÆÁÄ»½ØÍ¼ 2026-04-19 235510,0 |
||||
@ -0,0 +1,5 @@ |
|||||
|
85 |
||||
|
92 |
||||
|
78 |
||||
|
90 |
||||
|
88 |
||||
|
After Width: | Height: | Size: 90 KiB |
Loading…
Reference in new issue