Question

I've been working on a study project for ages and I think one of the things that is holding me back is not knowing how to correctly do the loop logic for a bit of code that aims to create a new chat room, or to connect users to an existing one.

This code seems to create a new room every time someone connects even if the roomname is identical. I'm pretty sure the approach is all wrong but not sure where start putting it right. Any help would be great. Even if it is to suggest a different approach.

    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);
    }

}
Was it helpful?

Solution

You have:

if (roomTemp.getName() == roomName) 

You mean:

if (roomTemp.getName().equals(roomName))

Do not compare strings with ==!

Use equalsIgnoreCase() if names are case-insensitive. Use trim() first if leading/trailing whitespace is an issue.

By the way, if an RMIRoomImpl's name never changes, you may find a Map<String,RMIRoomImpl> to be more convenient.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top