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

Java 入門實戰:鍵盤錄入學生信息統計最高/最低分

     編輯:Java 綜合教學

Java 入門實戰:鍵盤錄入學生信息統計最高/最低分

本示例演示如何使用 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

關鍵知識點總結

  1. Scanner 基本用法:next() 讀字符串(以空白分隔)、nextInt()、nextDouble() 讀數值。注意 nextLine() 讀整行含空格,混用時需處理換行符殘留。
  2. 對象數組:聲明 StuInformation[] 後,必須 逐個 new 對象,否則元素為 null 導致 NPE。
  3. 最大/最小值查找算法:假設第一個元素為極值,從第二個開始遍歷比較更新極值及索引,時間複雜度 O(n)。
  4. 資源關閉:sc.close() 釋放底層流,避免資源洩漏。

進階優化建議

  • 使用 ArrayList 替代固定長度數組,支持動態增刪。
  • 封裝 Student 類,提供構造器、Getter/Setter、toString(),符合 JavaBean 規範。
  • 異常處理:try-catch 捕獲 InputMismatchException,提示重新輸入非法數據。
  • 並列最高/最低分:用 List 收集所有極值學生,而非僅記錄首個。
  • 格式化輸出:System.out.printf("%-10s %5.1f%n", name, score) 對齊列寬。

這個小程序雖簡單,但涵蓋了「輸入→建模→處理→輸出」的完整編程流程,是通往更複雜業務邏輯開發的基石。

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