foxale foxale - 4 months ago 7
Java Question

Comparing strings seems to be not working properly

I'm currently working on my CharRoom project in Java 8. I'm trying to solve a bug, which appears when two clients connect with the same nickname. The simplest and also sufficient solution I've come up is to add " (1)" when a new client has the same nickname as one of the other clients.

for(int i = 0; i < newClientNum; i++) // loop not considering new client
{
System.out.println("Client " + i + " nickname: " + clients[i].nickname);
if(clients[newClientNum].nickname.equals(clients[i].nickname));
{
clients[newClientNum].nickname += " (1)";
System.out.println("New clients new nickname: " + clients[newClientNum].nickname);
i = -1;
}
}


Which seems to be incorrect.
Here is an output when there are two users connected with same nickname "user".

Client 0 nickname: user
New clients new nickname: user (1) (1) (1) (1) (1) (1) (1) ...
Client 0 nickname: user
New clients new nickname: user (1) (1) (1) (1) (1) (1) (1) ...
...

Answer

You have a trailing ; at the end of the if that doesn't belong there:

  if(clients[newClientNum].nickname.equals(clients[i].nickname));
        {
            clients[newClientNum].nickname += " (1)";
            System.out.println("New clients new nickname: " + clients[newClientNum].nickname);
            i = -1;
        }

This is equivalent to this code, which is not what you want:

if (clients[newClientNum].nickname.equals(clients[i].nickname)) {
    // do nothing
}

clients[newClientNum].nickname += " (1)";
System.out.println("New clients new nickname: " + clients[newClientNum].nickname);
i = -1;

Delete the ; at the end of the if statement.