Compare commits

...

No commits in common. 'ada602a35b77da6d2771890be14f520d6c06b0b3' and '5fc3a7f8cfa2cd597d0270147af91a9dafdfec7b' have entirely different histories.

  1. 38
      w7/ScoreCalculator.java
  2. 21
      w8/Pair.java
  3. 13
      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());
}
}
}

21
w8/Pair.java

@ -0,0 +1,21 @@
package w8;
public class Pair<K,V> {
private K key;
private V value;
public Pair(K key,V value){
this.key=key;
this.value=value;
}
public K getKey(){
return key;
}
public V getValue(){
return value;
}
public static <K, V> Pair<V, K> swap(Pair<K, V> pair) {
return new Pair<>(pair.getValue(), pair.getKey());
}
}

13
w8/Test.java

@ -0,0 +1,13 @@
package w7;
public class Test {
public static void main(String[] args) {
// 原始 Pair
Pair<String, Integer> original = new Pair<>("年龄", 18);
System.out.println("交换前:" + original);
// 调用静态 swap 方法交换键值
Pair<Integer, String> swapped = Pair.swap(original);
System.out.println("交换后:" + swapped);
}
}
Loading…
Cancel
Save