學(xué)生管理系統(tǒng)之添加學(xué)生解決學(xué)號(hào)重復(fù)問題
//添加學(xué)生
public static void addStudent(ArrayList<Student> array) {
//創(chuàng)建鍵盤錄入對(duì)象
Scanner sc = new Scanner(System.in);
//為了讓id能夠被訪問到包颁,我們就把id定義在循環(huán)的外面
String id;
//為了讓代碼能夠回到這里劣纲,用循環(huán)
while(true) {
System.out.println("請(qǐng)輸入學(xué)生學(xué)號(hào)");
// String id = sc.nextLine();
id = sc.nextLine();
//判斷學(xué)號(hào)有沒有被人占用
//定義標(biāo)記
boolean flag = false;
//遍歷集合,得到每一個(gè)學(xué)生
for(int x = 0; x < array.size(); x++) {
Student s = array.get(x);
//獲取該學(xué)生的學(xué)號(hào)混槐,和鍵盤錄入的學(xué)號(hào)進(jìn)行比較
if(s.getId().equals(id)) {
flag = true;//說明學(xué)號(hào)被占用了
break;
}
}
if(flag) {
System.out.println("你輸入的學(xué)號(hào)已經(jīng)被占用,請(qǐng)重新輸入");
}else {
break;//結(jié)束循環(huán)
}
}
System.out.println("請(qǐng)輸入學(xué)生姓名");
String name = sc.nextLine();
System.out.println("請(qǐng)輸入學(xué)生年齡");
String age = sc.nextLine();
System.out.println("請(qǐng)輸入學(xué)生居住地");
String address = sc.nextLine();
//創(chuàng)建學(xué)生對(duì)象
Student s = new Student();
s.setId(id);
s.setName(name);
s.setAge(age);
s.setAddress(address);
//把學(xué)生對(duì)象作為元素添加到集合
array.add(s);
//給出提示
System.out.println("添加學(xué)生成功");
}