亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

MapTest中putTest()方法這句/*StudentCls stu=students.get(ID);*/報空指針異常,求解?。?!

MapTest中putTest()方法這句/*StudentCls stu=students.get(ID);*/報空指針異常,求解?。?!

_坐看云起時 2016-04-12 21:59:35
import?java.util.HashSet; import?java.util.Set; /** ?*?學生類 ?*?@author?Administrator ?* ?*/ public?class?StudentCls?{ public?String?name; public?String?id; // public?Set<CourseCls>?couSet; public?StudentCls(String?name,String?id){ this.name=name; this.id=id; // this.couSet=new?HashSet<CourseCls>(); } } import?java.util.*; public?class?MapTest?{ public?Map<String,?StudentCls>?students; public?void?putTest(){ Scanner?sca=new?Scanner(System.in); int?i=0; while(i<3){ System.out.println("請輸入學生ID"); String?ID=sca.next(); StudentCls?stu=students.get(ID); if(stu==null){ System.out.println("請輸入學生姓名:"); String?name=sca.nextLine(); StudentCls?newstu=new?StudentCls(name,?ID); students.put(ID,?newstu); System.out.println("成功添加學生"+students.get(ID).name); i++; } else{ System.out.println("已有該學生!"); } } } public?void?ketSet(){ Set<String>?keyset=students.keySet(); System.out.println("總共有"+keyset.size()+"個學生"); for(String?id:keyset){ StudentCls?stu=students.get(id); if(stu!=null){ System.out.println("學生:"+stu.name); } } } public?static?void?main(String[]?args)?{ MapTest?mt=new?MapTest(); mt.putTest(); mt.ketSet(); } }
查看完整描述

1 回答

已采納
?
guozhchun

TA貢獻103條經驗 獲得超76個贊

students 只是聲明了并沒有定義,其是一個null,因此在調用students.get(ID)時會報錯。

可以定義一個構造函數給students賦值,也可以直接在聲明時定義:

public?Map<String,?StudentCls>?students?=?new?HashMap<String,?StudentCls>();


查看完整回答
1 反對 回復 2016-04-12
  • 1 回答
  • 0 關注
  • 1761 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號