求大神幫看看為什么添加來一個為null的姓名
package com.imooc.collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class MapTest {
?? ?
?? ?/**
?? ? * 用來裝學生類型對象
?? ? * @param args
?? ? */
?? ?public Map<String, Student> students;
?? ?public MapTest() {
?? ??? ?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 void testKeySet() {
?? ??? ?//通過keyset方法,返回map中的所有鍵的set集合
?? ??? ?Set<String> keySet = students.keySet();
?? ??? ?System.out.println("總共有 : " + students.size() + "個學生");
?? ??? ?for(String stuID : keySet) {
?? ??? ??? ?Student st = Student.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();
?? ?}
}
2018-08-16
null代表空,集合中沒有該ID-學生映射,所以可以添加學生=-=
2018-08-01
nall不是空嗎
2018-06-05
package com.imooc.collection;
import java.util.HashSet;
import java.util.Set;
public class Student {
?? ?public String id;
?? ?public String name;
?? ?public Set<Course> courses;
?? ?public Student(String iD2, String name2) {
?? ??? ?// TODO Auto-generated constructor stub
?? ?}
?? ?public static Student get(String stuID) {
?? ??? ?// TODO Auto-generated method stub
?? ??? ?return null;
?? ?}
?? ?public void Student(String id,String name) {
?? ??? ?this.id = id;
?? ??? ?this.name = name;
?? ??? ?
?? ??? ?this.courses = new HashSet<Course>();
?? ?}
}
2018-06-05
代碼沒貼全