需求:輸入 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());
}
}
}
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)可大幅提升擴充性。