diff --git a/w7/ScoreAvg.java b/w7/ScoreAvg.java new file mode 100644 index 0000000..ef862d3 --- /dev/null +++ b/w7/ScoreAvg.java @@ -0,0 +1,19 @@ +package w7; + +import java.io.BufferedReader; +import java.io.FileReader; + +public class ScoreAvg { + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new FileReader("scores.txt")); + 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); + } +} \ No newline at end of file diff --git a/w7/ScoreAvg2.java b/w7/ScoreAvg2.java new file mode 100644 index 0000000..eb8a263 --- /dev/null +++ b/w7/ScoreAvg2.java @@ -0,0 +1,36 @@ +package w7; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; + +public class ScoreAvg2 { + public static void main(String[] args) { + String path = "scores.txt"; + int sum = 0; + int count = 0; + + try (BufferedReader br = new BufferedReader(new FileReader(path))) { + String line; + while ((line = br.readLine()) != null) { + + try { + sum += Integer.parseInt(line); + count++; + } catch (NumberFormatException e) { + System.err.println("跳过无效数字行:" + line); + } + } + + if (count > 0) { + System.out.printf("平均分:%.2f%n", (double) sum / count); + } else { + System.out.println("未读取到有效成绩"); + } + } catch (IOException e) { + + System.err.println("读取文件失败:" + e.getMessage()); + e.printStackTrace(); + } + } +}