gpt4 book ai didi

java - 使用 Map 和不同类的 NullPointerException

转载 作者:行者123 更新时间:2023-12-01 13:22:18 24 4
gpt4 key购买 nike

我一直在尝试在 JAVA 中编写一个新类,其中我使用 Map 和 HashMap 将信息中继到不同的类,而不是在每个类中本地声明 Map。

我创建了一个新类“GetRoom.java”,它有 4 种不同的方法:

  • void addRoom(int id, Room room)
  • 房间 byID(int id)
  • boolean 值 containsID(int id)
  • 房间 doIexist()

代码如下:

private static Map<Integer, Room> hotelRooms = new HashMap<Integer, Room>();

public static void addRoom(int id, Room room){
hotelRooms.put(id, room);
}

public static Room byID(int id){
return hotelRooms.get(id);
}

public static Room doIexist(){
return hotelRooms.get(5);
}

public static boolean containsID(int id){
return hotelRooms.containsKey(id);
}

如果我在任何其他类中使用 byID 函数,它将返回 NullPointerException,而如果我使用 doIexist 函数,那么它将返回房间 ID 5。当调用 hotelRooms.size() 时,我可以看到我已经填充了它之前有 42 个房间,但无法在 GetRoom.java 之外引用它们

非常感谢任何帮助!

编辑:这是我调用代码的地方:

public static void Compose(ServerHandler Client, User theUser, Environment Server) throws Exception
{
User CurrentUser = Client.GetSession();
int RoomId = CurrentUser.CurrentRoomId;
Channel Socket = Client.Socket;
Room R = GetRoom.byID(RoomId); // If I change this to GetRoom.doIExist(); it will work

ServerMessage HeightMap = new ServerMessage(ServerEvents.HeightMap1);
HeightMap.writeUTF(R.GetModel().getMap());
HeightMap.Send(Socket);

ServerMessage RelativeMap = new ServerMessage(ServerEvents.HeightMap2);
String Map = R.GetModel().SerializeRelativeMap;
RelativeMap.writeUTF(Map);
RelativeMap.Send(Socket);
}

堆栈跟踪:

java.lang.NullPointerException
at messages.outgoing.rooms.LoadMapsMessageComposer.Compose(LoadMapsMessageComposer.java:30)
at messages.incoming.rooms.LoadMapsMessageEvent.run(LoadMapsMessageEvent.java:28)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

LoadMapsMessageComposer.java:30 是具有

的行

HeightMap.writeUTF(R.GetModel().getMap());

最佳答案

问题是,虽然您的 map 中可能添加了多个房间,但您没有currentRoomId 对应的房间。这意味着 get(id) 以及 byID 返回 null,然后您尝试调用该 null< 上的方法 值。

关于java - 使用 Map 和不同类的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21956257/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com