Browse Source

上传文件至 'w7-黄志楷-202506050318'

main
HuangZhikai 2 months ago
parent
commit
9a2f657dfd
  1. 71
      w7-黄志楷-202506050318/ScoreCalculator.java
  2. 18
      w7-黄志楷-202506050318/Scorecal.java
  3. 7
      w7-黄志楷-202506050318/score
  4. BIN
      w7-黄志楷-202506050318/修改前运行记录.png
  5. BIN
      w7-黄志楷-202506050318/修改后运行记录.png

71
w7-黄志楷-202506050318/ScoreCalculator.java

@ -0,0 +1,71 @@
import java.io.BufferedReader;
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 ScoreCalculator {
public static void main(String[] args) {
String fileName = "C:\\Users\\黄志楷\\Documents\\ocix\\学校相关\\jwork\\w7\\score";
double average = calculateAverageScore(fileName);
if (!Double.isNaN(average)) {
System.out.printf("平均分: %.2f%n", average);
}
}
/**
* 计算成绩文件的平均分
* @param fileName 文件名
* @return 平均分如果出错返回 NaN
*/
public static double calculateAverageScore(String fileName) {
int sum = 0;
int count = 0;
// 1. 检查文件是否存在
Path filePath = Paths.get(fileName);
if (!Files.exists(filePath)) {
System.err.println("错误: 文件 '" + fileName + "' 不存在!");
return Double.NaN;
}
// 2. 使用 try-with-resources 确保流自动关闭
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
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) {
System.err.println("错误: 文件中没有有效的成绩数据!");
return Double.NaN;
}
return (double) sum / count;
} catch (IOException e) {
// 读取错误
System.err.println("错误: 读取文件 '" + fileName + "' 时发生异常!");
System.err.println("详细信息: " + e.getMessage());
return Double.NaN;
}
// 无需显式 close(),try-with-resources 会自动处理
}
}

18
w7-黄志楷-202506050318/Scorecal.java

@ -0,0 +1,18 @@
import java.io.BufferedReader;
import java.io.FileReader;
public class Scorecal {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\黄志楷\\Documents\\ocix\\学校相关\\jwork\\w7\\score"));
String line;
int sum = 0;
int count = 0;
while ((line = br.readLine()) != null) {
sum += Integer.parseInt(line);
count++;
}
br.close();
System.out.println((double) sum / count);
}
}

7
w7-黄志楷-202506050318/score

@ -0,0 +1,7 @@
11
22
33
44
74
95
这个不是分数

BIN
w7-黄志楷-202506050318/修改前运行记录.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

BIN
w7-黄志楷-202506050318/修改后运行记录.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Loading…
Cancel
Save