student st=students.get(ID);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); //System.out.println(st); if(st==null) { System.out.println("请输入学生的名字"); String name=console.next(); student newStudent=new student(ID,name); students.put(ID, newStudent); System.out.println("成功添加学生"); i++; } else {System.out.println("改ID已经被占用"); continue; } } }public static void main(String[] args) { testMap tm=new testMap(); tm.testput();}public void testKeySet(){ Set<String> keyset=students.keySet(); for(String stuID:keyset) { student st=students.get(stuID); } }}请输入学生ID1Exception in thread "main" java.lang.NullPointerException at com.zhou.jihe.testMap.testput(testMap.java:24) at com.zhou.jihe.testMap.main(testMap.java:46)
1 回答
qq_Faraward_0
TA贡献1条经验 获得超0个赞
问题原因已经找到,初始化students时,用了pupublic void testMap()
{
this.students=new HashMap<String,student>();
}
构造方法使用了void,相当于并未对students进行初始化,所以指针指向为空,谢谢各位的关注
添加回答
举报
0/150
提交
取消