我目前正在使用Java 8中的CharRoom项目。我正在尝试解决一个错误,当两个客户端使用相同的昵称连接时出现该错误。我提出的最简单且最充分的解决方案是在新客户端与其他客户端具有相同昵称时添加“(1)”。
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;
}
}
这似乎是不正确的。 当有两个用户使用相同的昵称“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) ...
...
答案 0 :(得分:3)
;
末尾有if
,不属于那里:
if(clients[newClientNum].nickname.equals(clients[i].nickname)); { clients[newClientNum].nickname += " (1)"; System.out.println("New clients new nickname: " + clients[newClientNum].nickname); i = -1; }
这相当于此代码,这不是您想要的:
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;
删除;
声明末尾的if
。