2017-08-05 62 views
0

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

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

使用[计时器](https://docs.oracle.com/javase/7/docs/api/java/util/Timer.html)而不是睡眠。 – BladeMight

+0

我会如何在特定的时间使用计时器?计时器(时间)? –

+1

请看这里https://stackoverflow.com/questions/2258066/java-run-a-function-after-a-specific-number-of-seconds – BladeMight

回答

1

你的代码做一次第一次尝试不匹配的无限循环。

在你的循环的每个迭代中,除了增加计数器外,根本没有变化。所以柜台会永远增加(有一些延迟)。

看来你的代码背后的原因是String2更新了用户输入而不是在之外的循环内部。这样,在每次迭代中,您将有不同的String2进行比较。

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

1

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

相关问题