3 changed files with 49 additions and 0 deletions
Binary file not shown.
@ -0,0 +1,44 @@ |
|||
import java.io.BufferedReader; |
|||
import java.io.FileReader; |
|||
import java.io.IOException; |
|||
|
|||
public class ScoreCalculator { |
|||
public static void main(String[] args) { |
|||
String fileName = "scores.txt"; |
|||
calculateAverage(fileName); |
|||
} |
|||
|
|||
public static void calculateAverage(String fileName) { |
|||
int sum = 0; |
|||
int count = 0; |
|||
|
|||
// 使用try-with-resources确保流被关闭
|
|||
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) { |
|||
String line; |
|||
while ((line = br.readLine()) != null) { |
|||
try { |
|||
// 尝试解析数字
|
|||
int score = Integer.parseInt(line); |
|||
sum += score; |
|||
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.println("平均分: " + average); |
|||
} else { |
|||
System.out.println("没有有效的分数数据"); |
|||
} |
|||
|
|||
} catch (IOException e) { |
|||
System.out.println("错误: 无法读取文件 '" + fileName + "'"); |
|||
System.out.println("原因: " + e.getMessage()); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,5 @@ |
|||
85 |
|||
90 |
|||
78 |
|||
92 |
|||
88 |
|||
Loading…
Reference in new issue