首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 學生成績輸入存檔:陣列與檔案 I/O 實作

     編輯:Java 相關知識

學生資料管理:控制台輸入寫入檔案

需求:輸入 10 位學生的學號、姓名、4 門課成績,計算平均,存入文字檔。

完整程式碼(修正原始碼資源釋放問題)


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

public class StudentGradeRecorder {
    public static void main(String[] args) {
        final int STUDENT_COUNT = 10, SUBJECT_COUNT = 4;
        String[] names = new String[STUDENT_COUNT];
        String[] ids = new String[STUDENT_COUNT];
        int[][] scores = new int[STUDENT_COUNT][SUBJECT_COUNT];
        int[] averages = new int[STUDENT_COUNT];

        Scanner sc = new Scanner(System.in);
        // 使用 try-with-resources 確保關閉
        try (BufferedWriter bw = new BufferedWriter(new FileWriter("students.txt"))) {
            for (int i = 0; i < STUDENT_COUNT; i++) {
                System.out.print("請輸入第 " + (i+1) + " 位學生姓名:");
                names[i] = sc.next();
                System.out.print("請輸入學號:");
                ids[i] = sc.next();

                int sum = 0;
                for (int j = 0; j < SUBJECT_COUNT; j++) {
                    System.out.print("請輸入第 " + (j+1) + " 門成績:");
                    scores[i][j] = sc.nextInt();
                    sum += scores[i][j];
                }
                averages[i] = sum / SUBJECT_COUNT;

                // 寫入檔案:姓名 學號 成績1 成績2 成績3 成績4 平均
                bw.write(names[i] + " " + ids[i]);
                for (int s : scores[i]) bw.write(" " + s);
                bw.write(" " + averages[i]);
                bw.newLine();
            }
            System.out.println("資料已儲存至 students.txt");
        } catch (IOException e) {
            System.err.println("寫入檔案失敗:" + e.getMessage());
        }
    }
}

關鍵改進點

  • try-with-resources:JDK 7+ 自動關閉 BufferedWriter,避免資源洩漏。
  • 格式化輸出:使用空白分隔,便於後續 Scanner 或 String.split 讀取。
  • 例外處理:捕獲 IOException 並輸出錯誤訊息。

進階:物件導向重構


class Student {
    String id, name;
    int[] scores = new int[4];
    int average;
    // getter/setter/toString...
}

搭配 List 與 JSON/CSV 函式庫(如 Jackson、OpenCSV)可大幅提升擴充性。

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