当我在使用get(key)之后将不同的键放入hashmap时,不同的键显示相同的结果,我不知道为什么会发生这种情况
我有两个类,Room类和Office类
这是我的Room Class
import java.util.HashMap;
import java.util.Scanner;
public class Room {
private static int roomNumber;
private static String description;
public int getRoomNum(){return roomNumber;}
public String getDescription(){return description;}
public void setDescription(String description){
this.description=description;
}
public void setRoomNum(int roomNumber){
this.roomNumber=roomNumber;
}
public Scanner sc = new Scanner(System.in);
public static HashMap<Integer, Room> room = new HashMap<>();
public void askData(){
System.out.println("ENTER ROOM NUMBER:");
this.roomNumber=sc.nextInt();
sc.nextLine();
System.out.println("Enter description:");
this.description = sc.nextLine();
}
public String toString(){
return this.getRoomNum()+": "+this.getDescription();
}
public static void main(String[] args) {
Room r = new Office();
r.room.put(1,new Office(1,"java","asdfw"));
r.room.put(2,new Office(2,"jafasdfva","ghasdfasow"));
// ----------------------我的问题在这里
Room s = r.room.get(1);
Room s2 = r.room.get(2);
System.out.println(s.getRoomNum()+" . "+s.getDescription());
System.out.println(s2.getRoomNum()+" . "+s2.getDescription());
for(Integer keey: room.keySet()){
System.out.println(r.room.get(roomNumber));
}
}
//以下是结果
// 2。 jafasdfva
// 2。 jafasdfva
// 2:jafasdfva。 ghasdfasow
// 2:jafasdfva。 ghasdfasow
// -------------------------------
}
}
我有int键1和2,但是当我得到键1和2时,结果将显示键2两次,我不知道为什么会发生这种情况
// ------------------------------------
这是我的Office课程
import java.util.ArrayList;
import java.util.HashMap;
public class Office extends Room {
private String staffMembers;
public String enter,check;
public Office(int roomNumber,String description, String staffMembers){
this.setRoomNum(roomNumber);
this.setDescription(description);
this.staffMembers=staffMembers;
}
public Office(){}
public void askData(){
super.askData();
StringBuilder sb = new StringBuilder();
do{
System.out.println("Enter members in this room: ");
enter =sc.nextLine();
sb.append(enter+", ");
System.out.println("Enter Y to continule.");
check = sc.nextLine();
}while(check.equalsIgnoreCase("Y"));
this.staffMembers=sb+"";
this.room.put(this.getRoomNum(), new Office(this.getRoomNum(),this.getDescription(),staffMembers));
}
public String toString(){
return this.getRoomNum()+": "+this.getDescription()+". "+
this.staffMembers;
}
}