为什么我的代码运行出来报了空指针!
package com.immoc.collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class Maptest {
//用来橙装学生类型的对象
public Map<String,Student>students;
public void testMap(){
this.students = new HashMap<String,Student>();
}
/**
*
* 测试添加:判断学生ID是否被占用
*
*
*
* @param args
* @return
*/
public void testPut(){
//创建Scanner对象,用来获取输入的学生ID与姓名
Scanner console = new Scanner (System.in);
int i =0;
while(i<3){
System.out.println("请输入学生ID");
String ID = console.next();
/*判断ID是否被占用*/
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。getID。name");
i++;
}else{
System.out.println("该学生ID已被占用");
continue;
}
}
}
public void testKeySet(){
//通过keyset方法,返回Map所有键的SET集合
Set<String> keySet = students.keySet();
//便利ketSet,取得每一个键,在调用get取得每个键对应的Value
System.out.println("总共有:"+students.size()+"个学生");
//取得学生的容量
for(String stuId:keySet){
Student st = students.get(stuId);
if(st!=null)
System.out.println("学生:"+st.name);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Maptest mt = new Maptest();
mt.testPut();
mt.testKeySet();
}
}