本示例演示如何使用 Scanner 從控制台讀取學生姓名與成績,存入對象數組,並計算輸出最高分、最低分對應的學生信息。適合 Java 初學者練習面向對象基礎、數組操作、輸入輸出流與基本邏輯控制。
import java.util.Scanner;
// 學生信息實體類
class StuInformation {
String name;
double score;
}
public class TestStuInformation {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 1. 讀取學生人數
System.out.print("請輸入您要錄入的學生個數:");
int num = sc.nextInt();
StuInformation[] students = new StuInformation[num];
// 2. 循環錄入每個學生的姓名和成績
for (int i = 0; i < students.length; i++) {
students[i] = new StuInformation();
System.out.print("請輸入第 " + (i + 1) + " 個學生的姓名:");
students[i].name = sc.next(); // 讀取字符串(無空格)
System.out.print("請輸入第 " + (i + 1) + " 個學生的成績:");
students[i].score = sc.nextDouble(); // 讀取浮點數
}
// 3. 輸出所有學生信息
System.out.println("\t姓名\t成績");
for (StuInformation stu : students) {
System.out.println("\t" + stu.name + "\t" + stu.score);
}
// 4. 統計最高分
double max = students[0].score;
int maxIndex = 0;
for (int i = 1; i < students.length; i++) {
if (students[i].score > max) {
max = students[i].score;
maxIndex = i;
}
}
System.out.println("最高分是:" + students[maxIndex].name + "," + max);
// 5. 統計最低分
double min = students[0].score;
int minIndex = 0;
for (int i = 1; i < students.length; i++) {
if (students[i].score < min) {
min = students[i].score;
minIndex = i;
}
}
System.out.println("最低分是:" + students[minIndex].name + "," + min);
sc.close();
}
}
請輸入您要錄入的學生個數:3
請輸入第 1 個學生的姓名:張三
請輸入第 1 個學生的成績:85.5
請輸入第 2 個學生的姓名:李四
請輸入第 2 個學生的成績:92.0
請輸入第 3 個學生的姓名:王五
請輸入第 3 個學生的成績:78.5
姓名 成績
張三 85.5
李四 92.0
王五 78.5
最高分是:李四,92.0
最低分是:王五,78.5
next() 讀字符串(以空白分隔)、nextInt()、nextDouble() 讀數值。注意 nextLine() 讀整行含空格,混用時需處理換行符殘留。StuInformation[] 後,必須 逐個 new 對象,否則元素為 null 導致 NPE。sc.close() 釋放底層流,避免資源洩漏。ArrayList 替代固定長度數組,支持動態增刪。Student 類,提供構造器、Getter/Setter、toString(),符合 JavaBean 規範。try-catch 捕獲 InputMismatchException,提示重新輸入非法數據。System.out.printf("%-10s %5.1f%n", name, score) 對齊列寬。這個小程序雖簡單,但涵蓋了「輸入→建模→處理→輸出」的完整編程流程,是通往更複雜業務邏輯開發的基石。