Reputation: 1033
I'm trying to create a more advanced server-to-client program but I've stumbled onto a problem. I managed to ask the client to enter password, and if false it rejects the client.
However, I tried adding a while condition to the server: If client enters wrong password then ask him/her to re-enter password. But I tried using a scanner but don't think that's the solution as I receive errors.
Server side:
while(pw.equals("PASS")){
toClient.writeBytes("This pw " + pw + " is correct. Access granted! " + "\n");
}
toClient.writeBytes("Your password... " + pw + " is wrong. Please retry.");
pw = fromClient.readLine();
toClient.writeBytes(pw+ "\n");
}
Client side:
System.out.print("Enter your password: ");
myPass = fromUser.readLine();
toServer.writeBytes(myPass + "\n");
myPass = fromServer.readLine();
System.out.println(myPass);
The code is quite long. But everything works. The connection is set up, port number are the same. Only problem is I can't get the client to keep re-entering password until correct.
Do I have to make a while loop for client too? I'm not too sure...
Upvotes: 0
Views: 364
Reputation: 494
1st: Why is there a while loop on the server side?
2nd: The loop using a flag on the client side as suggested by @j0chn is correct way to do this.
Upvotes: 1
Reputation: 1113
I suggest a loop where you use a boolean to keep the loop alive.
Something like this:
boolean isCorrect = false;
System.out.print("Enter your password: ");
while(!isCorrect){
myPass = fromUser.readLine();
toServer.writeBytes(myPass + "\n");
if(myPass == fromServer.readLine()){
isCorrect = true;
}
myPass = fromServer.readLine();
System.out.println(myPass);
}
Maybe you have to change this part:
if(myPass == fromServer.readLine()){
to:
if(myPass.equals(fromServer.readLine()){
But remember that there are a lot of possibilities.
I hope it helps you.
Upvotes: 0