如何读取用户输入,一次一行来创建一个对象。然后哪个进入ArrayList?如您所见,当我输入名称时,它会将其分解并仅存储姓氏。或者如果我这样做:first-middle-last name,它存储中间名和姓氏。
我第一次输入名字,先调用search方法,看看这个名字是否已经存在于ArrayList中。这很好用。如果名称不在列表中,则搜索返回 null。然后提示输入和添加方法。
case 1: {
System.out.print("Enter the Students name: ");
String nameSearch = kbd.next();
Student stu = dc.search(nameSearch );
if (stu != null) {
System.out.println(stu);
}
else {
System.out.print("Enter name AGAIN: ");
String nameAdd= kbd.nextLine();
System.out.print("Enter grade (freshman, sophomore, junior, senior: ");
String categoryAdd = kbd.nextLine();
System.out.print("Major: ");
String majorAdd = kbd.nextLine();
System.out.print("Enter graduating year: ");
int yearAdd = kbd.nextInt();
System.out.print("Enter student ID: (xxxx.xxxx: ");
double idAdd= kbd.nextDouble();
dc.add(nameAdd, categoryAdd , majorAdd ,
yearAdd , idAdd);
}
break;
}
我的输入:
Enter the Students name: John Smith
Not Found(Search Method)
TEST
Enter name AGAIN: TEST2
Enter grade (freshman, sophomore, junior, senior: senior
Major: Computer Science
Enter graduating year: 2013
Enter student ID: 1234.4567
当我打印 ArrayList 时它是如何存储在对象中的:
Name: Smith
Grade: senior
Major: Computer Science
Graduating Year: 2013
Student ID: 1234.4567
添加方法:
public Student add(String name, String grade,
String major, int year, double id) {
Student newStu = new Student(addName, addGrade, addMajor, addYear, addId);
studentList.add(newStu );
System.out.println("Added!");
return null;
}