首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Java IO 流實戰:鍵盤輸入學生成績統計平均值並寫入檔案

     編輯:程式設計疑難解答

經典 Java IO 練習:從鍵盤讀取「姓名 成績」每行一筆,輸入 end# 結束,計算平均分並連同明細寫入 score.txt。本文提供完整、健壯、符合現代 Java 風格的參考實作。

需求分析

  • 輸入格式:張三 80(空格分隔),逐行讀取。
  • 結束標記:end#(題目原為 quit,以題目為準)。
  • 輸出:score.txt 包含所有明細行 + 最後一行平均分。
  • 異常處理:IO 異常、格式錯誤、空輸入。

參考實作 (Java 8+)

import java.io.*;
import java.util.*;

public class RecordScore {
    public static void main(String[] args) {
        // 輸出檔案路徑(建議相對路徑或可配置)
        File outFile = new File("score.txt");
        
        try (
            // 自動資源管理 (try-with-resources)
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            BufferedWriter bw = new BufferedWriter(new FileWriter(outFile))
        ) {
            String line;
            int count = 0;
            double sum = 0.0;
            
            System.out.println("請輸入學生姓名與成績(空格分隔),輸入 end# 結束:");
            
            while ((line = br.readLine()) != null) {
                line = line.trim();
                if ("end#".equals(line)) break; // 結束條件
                
                if (line.isEmpty()) continue; // 跳過空行
                
                String[] parts = line.split("\\s+"); // 正則分割,支援多空格
                if (parts.length < 2) {
                    System.err.println("格式錯誤(需:姓名 成績):" + line);
                    continue;
                }
                
                String name = parts[0];
                double score;
                try {
                    score = Double.parseDouble(parts[1]);
                } catch (NumberFormatException e) {
                    System.err.println("成績非數字:" + parts[1]);
                    continue;
                }
                
                // 寫入明細
                bw.write(line);
                bw.newLine();
                
                // 累計統計
                sum += score;
                count++;
            }
            
            // 輸出平均分
            if (count > 0) {
                double avg = sum / count;
                bw.write(String.format("平均成績:%.2f", avg));
                bw.newLine();
                System.out.printf("統計完成:共 %d 筆,平均 %.2f,已寫入 %s%n", count, avg, outFile.getAbsolutePath());
            } else {
                System.out.println("無有效資料。");
            }
            
        } catch (IOException e) {
            System.err.println("IO 錯誤:" + e.getMessage());
            e.printStackTrace();
        }
    }
}

關鍵改進點對比原始碼

問題原始碼改進版
讀取邏輯String[] s=st.split("") 在迴圈外,st 為 null迴圈內 readLine() 後立即 split("\\s+")
結束條件equals("quit")equals("end#") 依題目
資源管理手動 close(),異常時可能洩漏try-with-resources 自動關閉
平均分計算邏輯錯誤、未處理除零累計 sum/count,count>0 才計算
寫入平均分bw.write(score/count) 寫入 double 二進位String.format 格式化文字
異常處理捕獲 ArrayIndexOutOfBoundsException 誤導針對性捕獲 NumberFormatException、IOException

進階擴充建議

  • 單元測試:使用 ByteArrayInputStream 模擬標準輸入,驗證輸出檔案內容。
  • 指令引數:支援 java RecordScore input.txt output.txt 檔案管道模式。
  • 大數據量:改用 Files.lines() Stream API 或記憶體映射檔。
  • 編碼指定:new FileWriter(outFile, StandardCharsets.UTF_8) (Java 11+)。

執行範例

$ java RecordScore
請輸入學生姓名與成績(空格分隔),輸入 end# 結束:
張三 80
李四 90
王五 85
end#
統計完成:共 3 筆,平均 85.00,已寫入 /path/to/score.txt

$ cat score.txt
張三 80
李四 90
王五 85
平均成績:85.00

掌握 BufferedReader/Writer、try-with-resources、字串解析與異常處理,這類 IO 實務題即可輕鬆拿捏。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved