1 changed files with 51 additions and 0 deletions
@ -0,0 +1,51 @@ |
|||
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; |
|||
|
|||
// 1. 使用 try-with-resources 自动关闭流,确保资源释放
|
|||
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) { |
|||
String line; |
|||
|
|||
// 2. 逐行读取文件
|
|||
while ((line = br.readLine()) != null) { |
|||
// 跳过空行,避免 NumberFormatException
|
|||
line = line.trim(); |
|||
if (line.isEmpty()) { |
|||
continue; |
|||
} |
|||
|
|||
try { |
|||
// 3. 转换为整数并累加
|
|||
int score = Integer.parseInt(line); |
|||
sum += score; |
|||
count++; |
|||
} catch (NumberFormatException e) { |
|||
// 处理数字格式错误
|
|||
System.err.println("警告:无法将内容 '" + line + "' 转换为整数,已跳过。"); |
|||
} |
|||
} |
|||
|
|||
// 4. 计算并输出平均分
|
|||
if (count > 0) { |
|||
double average = (double) sum / count; |
|||
System.out.println("成绩文件读取完成。"); |
|||
System.out.println("总分:" + sum); |
|||
System.out.println("人数:" + count); |
|||
System.out.printf("平均分:%.2f%n", average); |
|||
} else { |
|||
System.out.println("文件中没有有效的成绩数据。"); |
|||
} |
|||
|
|||
} catch (IOException e) { |
|||
// 处理文件不存在、读取错误等IO异常
|
|||
System.err.println("读取文件时发生错误:" + e.getMessage()); |
|||
e.printStackTrace(); |
|||
} |
|||
} |
|||
} |
|||
Loading…
Reference in new issue