Browse Source

score

master
zhaoyinghui 2 months ago
parent
commit
25722ee823
  1. 82
      W7/ScoreAverage.java
  2. BIN
      W7/score成功形式.png
  3. BIN
      W7/score报错形式.png

82
W7/ScoreAverage.java

@ -0,0 +1,82 @@
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class ScoreAverage {
public static void main(String[] args) {
String fileName = "scores.txt";
int sum = 0;
int count = 0;
// 尝试找到文件
File file = findFile(fileName);
if (file == null) {
System.err.println("错误:找不到文件 " + fileName);
System.err.println("请将 " + fileName + " 放在以下任意位置:");
System.err.println(" 1. " + System.getProperty("user.dir"));
System.err.println(" 2. " + System.getProperty("java.class.path") + " 目录下");
System.err.println("\n或者使用绝对路径创建文件。");
return;
}
// 使用 try-with-resources 自动关闭流
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
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.println("平均分: " + average);
} else {
System.out.println("错误:没有有效的成绩数据。");
}
} catch (IOException e) {
System.err.println("读取文件时出错: " + e.getMessage());
}
}
// 辅助方法:在多个位置查找文件
private static File findFile(String fileName) {
// 1. 当前工作目录
File file = new File(fileName);
if (file.exists()) {
return file;
}
// 2. 用户主目录
file = new File(System.getProperty("user.home"), fileName);
if (file.exists()) {
return file;
}
// 3. 桌面目录
file = new File(System.getProperty("user.home") + "/Desktop", fileName);
if (file.exists()) {
return file;
}
return null;
}
}

BIN
W7/score成功形式.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 335 KiB

BIN
W7/score报错形式.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 356 KiB

Loading…
Cancel
Save