3 changed files with 39 additions and 1 deletions
@ -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()); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -1,4 +1,4 @@ |
|||||
package w7; |
package w8; |
||||
|
|
||||
public class Pair<K,V> { |
public class Pair<K,V> { |
||||
private K key; |
private K key; |
||||
Loading…
Reference in new issue