请输入学生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);
}
}
}
}
求大神帮忙解答
构造方法的格式是 修饰词+类名{} 和返回值有关的都不能加
问题原因已经找到,初始化students时,用了pupublic void testMap()
{
this.students=new HashMap<String,student>();
}
构造方法使用了void,相当于并未对students进行初始化,所以指针指向为空,谢谢各位的关注