while( i < 3){
System.out.println("请输入学生ID:");
String ID = console.next();
//判断该ID是否被占用
// 指定 输入的ID 与 student的关系
//此时ID 已与 相应的student 绑定
Student st = students.get(ID);
if ( st == null){
//提示输入学生姓名
System.out.println("请输入学生姓名:");
String name = console.nextLine();
//新的 学生对象
Student newStudent = new Student(ID, name);
students.put(ID, newStudent);
System.out.println("成功添加学生:"+students.get(ID).name);
i++;
} else {
System.out.println("该学生已被占用!!");
continue;
}
}ID是从键盘输入的字符串,st是根据你输入的ID从Map--students中取得的value值。首先进行判断,如果st为空,那么意味着这个ID没有与之匹配的value值,也就是不存在,说明我们可以去添加这个ID。现在这个ID已经确定下来了,那么还差Student中的name。再次从键盘读入,取得name。至此,ID,name都全了,用Student(String,String)的构造方法新建一个Student对象---newStudent。要记得students是HashMap<String,Student>,尖括号里面的String其实就是ID,newStudent对象其实就是Student。