我多年来一直在研究一个研究项目,我认为其中一个阻碍我的事情就是不知道如何正确地为一些旨在创建新聊天室的代码做循环逻辑,或者将用户连接到现有用户。
即使房间名称相同,此代码似乎每次有人连接时都会创建一个新房间。我很确定这种方法是错的,但不确定从哪里开始正确。 任何帮助都会很棒。即使是建议采用不同的方法。
public void connect(RMIChatClient theClient, String roomName)
throws RemoteException {
// check if room exists and pass the client to the relevant room
// cycle list of rooms
Iterator<RMIRoomImpl> it = myRoomsList.iterator();
while (it.hasNext()) {
RMIRoomImpl roomTemp = (RMIRoomImpl) it.next();
if (roomTemp.getName() == roomName) {
//if there is a match then just add the client to the room
roomTemp.addClient(theClient);
System.out.println("Bound Client: " + theClient + "in Existing Room:"
+ roomName);
match = true;
return;
}
}
if (match != true) {
// if there is no match then create a new room and pass the first client
RMIRoomImpl newRoom = new RMIRoomImpl(roomName, theClient);
System.out.println("new room created: " + roomName);
myRoomsList.add(newRoom);
System.out.println("Bound Client: " + theClient + "in Room:"
+ roomName);
}
}
答案 0 :(得分:1)
你有:
if (roomTemp.getName() == roomName)
你的意思是:
if (roomTemp.getName().equals(roomName))
Do not compare strings with ==
!
如果名称不区分大小写,请使用equalsIgnoreCase()
。如果前导/尾随空格是个问题,请先使用trim()
。
顺便说一下,如果RMIRoomImpl
的名称永远不会改变,您可能会发现Map<String,RMIRoomImpl>
更方便。