0

I am learning java and so far I have created a password check using if statements. However I inserted my working String check into a while loop and added Thread.sleep(3000); for a 3 second delay, however once I completed that my GUI just keeps lagging and freezing on one page as if the button was pressed. Can somebody please show me how to make a working example of a code with a String check and after a certain amount of tries a delay to stop the user from trying again? (here is what I have:)

    //var declaration
    boolean match = false;
    String1 = "hi";
    String2 = (I know this is not code but just to omit some code:) userInput
    int time = 3000;
    int attempt = 0;
    //check
    while(!match && attempt < (maximumTries+1)){
        if(String1.equals(String2)){
            System.out.print("match");
        }
        else if(attempt < 11){
            attempt++;
            System.out.println("Failed:" + attempt);
        }
        else{
            attempt++;
            System.out.println("Please try again later you have:" + attempt + "failed attempts");
            try{
                Thread.sleep(time);
            }
            catch(InterruptedException ex) {
                Logger.getLogger(PasswordEntry.class.getName()).log(Level.SEVERE, null, ex);
            }
            time = time + 1000;//1 second more every time
        }
    }
J. Doe
  • 29
  • 7

2 Answers2

1

your code is doing an infinite loop once the first attempt does not match.

in each of the iterations of your loop there is no change at all, aside from incrementing the counter. so the counter just increases forever (with some delays in between).

it seems the reasoning behind your code was that String2 got updated with user input inside the loop not outside. This way, on each iteration you would have a different String2 to compare against.

That's your issue, not the way you delay between attempts (that for sure can be improved in any case).

albert_nil
  • 1,648
  • 7
  • 9
1

You should avoid using the Thread.sleep option since it completely freezes the main thread. You could also try creating another thread, which will be frozen and later in gives a callback to the main one. For example through a boolean variable. I'd also agree on the timer solution mentioned by BladeMight.