java- 如何创建延迟一定时间的字符串检查?

java- How do I create a String check with a delay of a certain amount of time?

我正在学习 java,到目前为止,我已经使用 if 语句创建了密码检查。但是我将我的工作字符串检查插入了一个 while 循环并添加了 Thread.sleep(3000);延迟 3 秒,但是一旦我完成,我的 GUI 就会在一页上保持滞后和冻结,就像按下按钮一样。有人可以告诉我如何制作一个带有字符串检查的代码的工作示例,并在一定数量的尝试后延迟以阻止用户再次尝试吗? (这是我的:)

    //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
        }
    }

一旦第一次尝试不匹配,您的代码就会执行无限循环。

在循环的每次迭代中,除了递增计数器外,根本没有任何变化。所以计数器永远增加(中间有一些延迟)。

您的代码背后的原因似乎是 String2 是根据用户输入更新的在循环内而不是在循环外。这样,在每次迭代中,您都会有一个不同的 String2 进行比较。

那是你的问题,而不是你在尝试之间延迟的方式(在任何情况下肯定可以改进)。

您应该避免使用 Thread.sleep 选项,因为它会完全冻结主线程。您也可以尝试创建另一个线程,该线程将被冻结,稍后会回调主线程。例如通过布尔变量。我也同意 BladeMight 提到的计时器解决方案。