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

Java 泛型與 ArrayList 實戰:學員資訊錄入與展示

     編輯:Java 綜合教學

需求

輸入學員學號、姓名、年齡,學號為 0 結束,最後列表顯示所有學員。

領域模型

public class Student {
    public int id;
    public String name;
    public int age;
    public Student() {}
    public Student(int id, String name, int age) {
        this.id = id; this.name = name; this.age = age;
    }
}

主程式

public class StudentDemo {
    public static void main(String[] args) {
        System.out.println("***** 錄入學員資訊,學號為 0 結束 *****");
        Scanner sc = new Scanner(System.in);
        List<Student> list = new ArrayList<>();

        while (true) {
            Student s = new Student();
            System.out.print("請輸入學號:");
            s.id = sc.nextInt();
            if (s.id == 0) {
                System.out.println("結束錄入!");
                break;
            }
            System.out.print("請輸入姓名:");
            s.name = sc.next();
            System.out.print("請輸入年齡:");
            s.age = sc.nextInt();
            list.add(s);
        }

        System.out.println("\n學員資訊如下:");
        System.out.println("學號\t姓名\t年齡");
        for (Student s : list) {
            System.out.println(s.id + "\t" + s.name + "\t" + s.age);
        }
    }
}

執行範例

***** 錄入學員資訊,學號為 0 結束 *****
請輸入學號:1001
請輸入姓名:張三
請輸入年齡:20
請輸入學號:1002
請輸入姓名:李四
請輸入年齡:22
請輸入學號:0
結束錄入!

學員資訊如下:
學號	姓名	年齡
1001	張三	20
1002	李四	22

關鍵點

  • ArrayList<Student> 泛型確保型別安全。
  • 採用增強 for 迴圈遍歷,碼簡潔無需 Iterator。
  • Scanner 記得關閉或用 try-with-resources(Java 7+)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved