代码是按照老师的写的,运行到student st=students.get(ID);抛出异常
请输入学生ID
1
Exception in thread "main" java.lang.NullPointerException
at com.zhou.jihe.testMap.testput(testMap.java:24)
at com.zhou.jihe.testMap.main(testMap.java:43)
package com.zhou.jihe;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class testMap {
public Map<String,student> students;
public void testMap()
{
this.students=new HashMap<String,student>();
}
public void testput()
{
Scanner console=new Scanner(System.in);
int i=0;
while(i<3)
{
System.out.println("请输入学生ID");
String ID=console.next();
student st=students.get(ID);
if(st==null)
{
System.out.println("请输入学生的名字");
String name=console.next();
student newStudent=new student(ID,name);
students.put(ID, newStudent);
System.out.println("成功添加学生"+students.get(ID).name);
i++;
}
else
{System.out.println("改ID已经被占用");
continue;
}
}
}
public static void main(String[] args) {
testMap tm=new testMap();
tm.testput();
tm.testKeySet();
// student s=new student("1","小明");
// System.out.println(s.id);
}
public void testKeySet()
{
Set<String> keyset=students.keySet();
System.out.println("总共有"+students.size()+"个学生");
for(String stuID:keyset)
{
student st=students.get(stuID);
if(st!=null)
{
System.out.println("学生:"+st.name);
}
}
}
}
求大神帮忙解答