Browse Source

重构“裸奔”代码

main
ZhangYuhan 2 months ago
parent
commit
1b8bb595ea
  1. 58
      w7/ScoreAvg.java
  2. 4
      w7/scores
  3. BIN
      w7/代码(上).png
  4. BIN
      w7/代码(下).png

58
w7/ScoreAvg.java

@ -0,0 +1,58 @@
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ScoreAvg {
public static void main(String[] args) {
String fileName = "scores.txt";
BufferedReader br = null;
int sum = 0;
int count = 0;
// ========================
// 题目要求:try catch finally
// ========================
try {
// 1. 打开文件
br = new BufferedReader(new FileReader(fileName));
// 2. 读取每一行
String line;
while ((line = br.readLine()) != null) {
line = line.trim();
if (line.isEmpty()) continue;
try {
int score = Integer.parseInt(line);
sum += score;
count++;
} catch (NumberFormatException e) {
System.out.println("格式错误:" + line);
}
}
// 3. 输出结果
System.out.println("总分:" + sum);
System.out.println("平均分:" + (double) sum / count);
} catch (IOException e) {
// 异常处理
System.out.println("文件操作失败!");
e.printStackTrace();
} finally {
// ========================
// finally:必须执行,关闭流!
// 题目要求必须写这里!
// ========================
try {
if (br != null) {
br.close();
System.out.println("流已关闭!");
}
} catch (IOException e) {
System.out.println("关闭失败!");
}
}
}
}

4
w7/scores

@ -0,0 +1,4 @@
90
85
95
88

BIN
w7/代码(上).png

Binary file not shown.

After

Width:  |  Height:  |  Size: 162 KiB

BIN
w7/代码(下).png

Binary file not shown.

After

Width:  |  Height:  |  Size: 185 KiB

Loading…
Cancel
Save