輸入學員學號、姓名、年齡,學號為 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> 泛型確保型別安全。