Milan Milan - 3 months ago 27
Java Question

Limit login attempt in Java

I am trying to limit the maximum login attempts to 3. However, my code below uses all the attempts before the user can get a chance to press the login button again. How would I fix this?

private void executeLogin() {

String userNameStr = userNameTF.getText();
String passWordStr = passWordTF.getText();

int totalAttempts = 3;

while (totalAttempts != 0) {

if (userNameStr == "temp" && passWordStr == "pass") {


System.out.println("Login Correct!");
return;

} else {


System.out.println("Incorrect Login");

totalAttempts--;
System.out.println(totalAttempts);

}

}

if (totalAttempts == 0) {

System.out.println("Maximum number of attempts exceeded");
}
}

Answer

Whenever, the executeLogin() will be invoked, the previous value of totalAttempts will be erased and it will be again initialized to 3. To control this, you can make the totalAttempts as global `int totalAttempts= 3; private void executeLogin() {

String userNameStr = userNameTF.getText();
String passWordStr = passWordTF.getText();

if (totalAttempts != 0) {
    if (userNameStr == "temp" && passWordStr == "pass") {
        System.out.println("Correct");
    else {
        System.out.println("Incorrect");
        totalAttempts--;

} else {
    System.out.println("Maximum number of attempts exceeded");
}

}` Or if you are declaring it inside the class make it static.

Comments