LiZifan 2 months ago
parent
commit
5fc3a7f8cf
  1. 38
      w7/ScoreCalculator.java
  2. 2
      w8/Pair.java
  3. 0
      w8/Test.java

38
w7/ScoreCalculator.java

@ -0,0 +1,38 @@
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ScoreCalculator {
public static void main(String[] args) {
String filePath = "scores.txt";
int sum = 0;
int count = 0;
// try-with-resources 自动关闭流,无需手动 close()
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
try {
// 处理数字格式错误
int score = Integer.parseInt(line.trim());
sum += score;
count++;
} catch (NumberFormatException e) {
System.err.println("警告:无法解析分数 '" + line + "',跳过该数据。");
}
}
if (count > 0) {
double average = (double) sum / count;
System.out.printf("平均分:%.2f%n", average);
} else {
System.out.println("文件中没有有效分数数据。");
}
} catch (java.io.FileNotFoundException e) {
System.err.println("错误:文件不存在,请检查路径 '" + filePath + "'。");
} catch (IOException e) {
System.err.println("错误:读取文件失败 - " + e.getMessage());
}
}
}

2
w7/Pair.java → w8/Pair.java

@ -1,4 +1,4 @@
package w7;
package w8;
public class Pair<K,V> {
private K key;

0
w7/Test.java → w8/Test.java

Loading…
Cancel
Save