為什么我的代碼運行出來報了空指針!
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(){
?? ??? ??? ?//創(chuàng)建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();
?? ??? ??? ??? ??? ?//創(chuàng)建學生對象
?? ??? ??? ??? ??? ?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,取得每一個鍵,在調(diào)用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();
?? ??? ?
?? ??? ?
?? ??? ?
?? ?}
}
2015-11-13
public void testMap(){
?? ??? ??? ?
?? ??? ??? ?this.students = new HashMap<String,Student>();
?? ???? }
把void去掉就可以了。
2015-09-17
? ??????public void testMap(){
?? ??? ??? ?
?? ??? ??? ?this.students = new HashMap<String,Student>();
?? ???? }
? ?這里你是想寫構造方法吧?
? ?你寫的這個方法沒有執(zhí)行,students沒有初始化。
? ?構造方法:
????????public Maptest(){
?? ??? ??? ?
?? ??? ??? ?this.students = new HashMap<String,Student>();
?? ???? }
? ?創(chuàng)建Maptest時,students就會初始化。
? ? ? ? ? ? ?
2015-09-17