Student Grade Calculator
題目說明
請實作一個學生成績計算系統。系統中有一個 Student
類別,代表一個學生的資訊。每個學生有姓名(name)、學號(id)和最多10個科目的分數(scores)。所有的學生都屬於同一個學校(school)。
系統需要能夠:
- 新增學生資料
- 為學生添加科目分數
- 計算學生的平均分數
- 顯示學生的完整資訊
請補齊下列程式碼中的底線空白處,完成題目要求。
程式模板(請填入下列程式碼中的底線空白處)
import java.util.Scanner;
class Student {
private String name;
private String id;
private int[] scores; // 儲存學生的分數(最多10科)
private int scoreCount; // 記錄目前已添加的分數數量
private final static String schoolName = "Technology University";
// 建構子
public Student(String _____, String _____) {
_____ = name;
_____ = id;
_____ = new int[10]; // 最多存10個分數
_____ = 0; // 初始分數數量為0
}
public void addScore(int score) {
if (!validScore(_____)) {
System.out.println("Invalid score: " + score + " (must be between 0 and 100)");
return;
}
if (_____ < 10) { // 確認還有空間可以添加分數
_____[_____] = score;
_____++;
} else {
System.out.println("Cannot add more scores, maximum is 10");
}
}
private boolean validScore(int score) {
return _____ >= 0 && _____ <= 100;
}
public double calculateAverage() {
if (_____ == 0) {
return 0;
}
int sum = 0;
for (int i = 0; i < _____; i++) {
sum += _____[i];
}
return (double) _____ / _____;
}
public String toString() {
return _____ + " Student - ID: " + _____ + ", Name: " + _____ +
", Average Score: " + String.format("%.2f", calculateAverage()) ;
}
}
public class GradeCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numStudents = scanner.nextInt();
scanner.nextLine(); // consume newline
for (int i = 0; i < numStudents; i++) {
String id = scanner.nextLine();
String name = scanner.nextLine();
int numScores = scanner.nextInt();
scanner.nextLine(); // consume newline
Student student = new Student(name, id);
for (int j = 0; j < numScores; j++) {
int score = scanner.nextInt();
student.addScore(score);
}
if (numScores > 0) {
scanner.nextLine();
}
System.out.println(student);
}
scanner.close();
}
}
輸入
第一行是一個整數 N,表示有 N 個學生的資料。
對於每個學生,輸入包括:
第一行:學生的學號(字串)
第二行:學生的姓名(字串)
第三行:一個整數 M,表示有 M 個科目的分數
第四行:M 個整數,表示各科目的分數(0-100之間)
輸出
對於每個學生,輸出一行包含學校名稱、學生的學號、姓名和平均分數(保留兩位小數)。
如果輸入的分數無效(不在0-100之間),會顯示錯誤訊息,且該分數不計入平均值。
範例輸入 #1
2
S001
John Smith
3
85 92 78
S002
Mary Johnson
4
95 88 76 90
範例輸出 #1
Technology University Student - ID: S001, Name: John Smith, Average Score: 85.00
Technology University Student - ID: S002, Name: Mary Johnson, Average Score: 87.25
說明:輸入了兩名學生的資料。第一名學生John Smith,學號S001,有三科成績:85, 92, 78,平均分是85.00。第二名學生Mary Johnson,學號S002,有四科成績:95, 88, 76, 90,平均分是87.25。
範例輸入 #2
1
S004
Emma Davis
3
95 -10 88
範例輸出 #2
Invalid score: -10 (must be between 0 and 100)
Technology University Student - ID: S004, Name: Emma Davis, Average Score: 91.50
說明:輸入了一名學生Emma Davis的資料,學號S004,有三科成績:95, -10, 88。由於-10不是有效分數,系統顯示錯誤訊息,並且不計入平均值計算。因此平均分是(95+88)/2=91.50。
Comments