You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

33 lines
1.2 KiB

package w7;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class SaveAerage {
public static void main([String[] args]){
String filePath = "scores.txt";
int sum = 0;
int count = 0;
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
int score = Integer.parseInt(line.trim());
sum += score;
count++;
} catch (NumberFormatException e) {
System.out.printlm("数字格式错误,跳过无效数据: " + line);
}
}
if (count == 0) {
System.out.println("文件中没有有效成绩数据");
} else {
double average = (double) sum / count;
System.out.println("平均分: %.2f%n" ,average);
}
} catch (java.io.FileNotFoundException e) {
System.err.println("错误:文件不存在 —— " + filePath);
} catch (IOException e) {
System.err.println("错误:读取文件时发生异常 —— " + e.getMessage());
}
}