package ArrayListDemo;
import java.util.ArrayList;
import java.util.Scanner;
/*案例:存盤學生物件并遍歷
需求:創建一個存盤學生物件的集合,并使用鍵盤錄入的方法錄入資料,然后將資料存盤到集合中遍歷并輸出
分析:1.創建學生類,成員變數型別為String 因為是獲取鍵盤錄入的資料
2.創建集合物件
3.創建學生物件并接受鍵盤錄入的數值
4.使用add方法將學生物件加入到集合中
5.遍歷集合并輸出
* */
public class ArrayListDemo03 {
public static void main(String[] args) {
//創建空集合物件
ArrayList<Student> arr = new ArrayList<Student>();
//回圈輸入學生資料
Scanner sc = new Scanner(System.in);
System.out.println("請輸入您所需要輸入的學生個數");
int num = sc.nextInt();
if (true) {
for (int i = 0; i < num; i++) {
AddArr(arr);
}
//回圈遍歷
for (int x = 0; x < arr.size(); x++) {
Student s = arr.get(x);
System.out.println(s.getName() + s.getAge());
}
}
}
//定義輸入學生資料的方法
public static void AddArr(ArrayList<Student> arr){
//創建scanner物件
Scanner sc=new Scanner(System.in);
System.out.println("請輸入學生名字");
String name=sc.nextLine();
System.out.println("請輸入學生年齡");
String age=sc.nextLine();
//創建學生物件
Student s=new Student();
s.setName(name);
s.setAge(age);
arr.add(s);
// System.out.println(arr);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/441933.html
標籤:其他
下一篇:理解“閉包”
