Browse Source

上传文件至 'w8'

main
wangyandi 2 months ago
parent
commit
4a84d11d0e
  1. 20
      w8/ScoreRaw.java
  2. 45
      w8/ScoreTest.java
  3. 5
      w8/scores.txt
  4. BIN
      w8/运行截屏比对.png

20
w8/ScoreRaw.java

@ -0,0 +1,20 @@
import java.io.BufferedReader;
import java.io.FileReader;
public class ScoreRaw {
public static void main(String[] args) {
// 【错误点】:没有 try-catch,如果文件不存在会直接报错
// 【错误点】:没有定义 sum
int sum = 0;
int count = 0;
// 【错误点】:写法不严谨,资源未在 finally 中关闭,容易造成内存泄漏
BufferedReader br = new BufferedReader(new FileReader("scores.txt"));
String line;
while ((line = br.readLine()) != null) {
// 【错误点】:如果文件里有空行或文字,parseInt 会报错崩溃
sum += Integer.parseInt(line);
}
}
}

45
w8/ScoreTest.java

@ -0,0 +1,45 @@
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ScoreTest {
public static void main(String[] args) {
// 定义文件路径
String fileName = "scores.txt";
// 初始化变量
int sum = 0; // 总分
int count = 0; // 人数(行数)
// 使用 try-with-resources 自动关闭流
// 即使发生异常,br 也会自动关闭
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
// 循环读取每一行
while ((line = br.readLine()) != null) {
try {
// 尝试将字符串转换为整数并累加
sum += Integer.parseInt(line);
count++;
} catch (NumberFormatException e) {
// 处理数字格式错误(例如文件中有空行或文字)
System.out.println("警告:发现无效数字格式 -> " + line + ",已跳过该行。");
}
}
// 计算并输出结果
if (count > 0) {
System.out.println("读取完成。");
System.out.println("总分: " + sum);
System.out.println("平均分: " + ((double) sum / count));
} else {
System.out.println("文件为空或没有有效数据。");
}
} catch (IOException e) {
// 处理文件找不到或读取错误
System.err.println("错误:无法读取文件 '" + fileName + "'。请确保文件存在且路径正确。");
e.printStackTrace();
}
}
}

5
w8/scores.txt

@ -0,0 +1,5 @@
85
90
78
100
60

BIN
w8/运行截屏比对.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 126 KiB

Loading…
Cancel
Save