1 changed files with 37 additions and 0 deletions
@ -0,0 +1,37 @@ |
|||
import java.io.BufferedReader; |
|||
import java.io.FileReader; |
|||
import java.io.IOException; |
|||
|
|||
public class ScoreAverage { |
|||
public static void main(String[] args) { |
|||
String fileName = "scores.txt"; |
|||
int sum = 0; |
|||
int count = 0; |
|||
|
|||
// try-with-resources 会自动关闭流,无需手动调用 close()
|
|||
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) { |
|||
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) { |
|||
System.out.println("文件中没有有效成绩数据,无法计算平均分。"); |
|||
} else { |
|||
double average = (double) sum / count; |
|||
System.out.printf("平均分:%.2f%n", average); |
|||
} |
|||
|
|||
} catch (IOException e) { |
|||
System.err.println("文件读取错误:" + e.getMessage()); |
|||
} catch (Exception e) { |
|||
System.err.println("发生意外错误:" + e.getMessage()); |
|||
} |
|||
} |
|||
} |
|||
Loading…
Reference in new issue