1 changed files with 47 additions and 0 deletions
@ -0,0 +1,47 @@ |
|||
import java.io.BufferedReader; |
|||
import java.io.FileReader; |
|||
import java.io.IOException; |
|||
|
|||
public class ScoreAverageCalculator { |
|||
public static void main(String[] args) { |
|||
String filePath = "scores.txt"; |
|||
int sum = 0; |
|||
int count = 0; |
|||
|
|||
// 使用 try-with-resources 确保流自动关闭 |
|||
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) { |
|||
String line; |
|||
while ((line = br.readLine()) != null) { |
|||
// 跳过空行 |
|||
if (line.trim().isEmpty()) { |
|||
continue; |
|||
} |
|||
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.println("有效成绩数量: " + count); |
|||
System.out.println("总分: " + sum); |
|||
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()); |
|||
} |
|||
} |
|||
} |
|||
Loading…
Reference in new issue