Browse Source

上传文件至 'w7'

main
Jiayuheng 2 months ago
parent
commit
8a3e086ac8
  1. BIN
      w7/ScoreCalculator.class
  2. 44
      w7/ScoreCalculator.java
  3. 5
      w7/scores.txt

BIN
w7/ScoreCalculator.class

Binary file not shown.

44
w7/ScoreCalculator.java

@ -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());
}
}
}

5
w7/scores.txt

@ -0,0 +1,5 @@
85
90
78
92
88
Loading…
Cancel
Save