Reputation: 1015
I have a real newbie question. I want to ask the user for a password 3 times. After 3 times, if the wrong password is still entered, I want to exit the block.
This is what I have at the moment. But I'm stuck with the final statement. If the password is not correct the first time, the final 'false' will overwrite the 'true' statement in the while loop.
public boolean checkOwnerPassword2()
{
String password = "123";
String s = userInput();
if(s.equals(password))
return true;
else
{
int i = 0;
while(!(s.equals(password)) && i < 2)
{
if(s.equals(password))
return true;
else
{
System.out.println("Try again");
s = userInput();
i++;
}
}
}
return false;
}
Somewhere else Im using the following code:
if(checkOwnerPassword2())
addPrizeToList();
else
System.out.println("sorry you can't add prize!");
This is my edited version:
Upvotes: 3
Views: 6823
Reputation: 1095
The times of trying should be stored in database. like this:
username | password | details | password_try_times
Once the user try a wrong password, password_try_times should add 1. And if the user login successfully, the password_try_times will be set to 0.
If you use Spring-security, you can add this process to the UserAuthenticationProviderService
method.
Hope this will help:)
Upvotes: 0
Reputation: 297
problem with your code is that when you enter correct password
!(s.equals(password)) evaluates to false in a way (!(true)) . And you have used end so first condition evaluates to false and second true. And program left the while loop and returns false.
Upvotes: 0
Reputation: 26094
The simplest way you can do like this.
public boolean checkOwnerPassword2() {
String password = "123";
int i = 0;
while (i < 3) {
System.out.println("Enter password");
String s = userInput();
if (s.equals(password)){
return true;
}
i++;
}
return false;
}
from your code
while(!(s.equals(password)) && i < 2)
replace to like this
while(i < 2)
this if condition will take care of the password verification
if(s.equals(password))
return true;
Upvotes: 2