2017-08-05 60 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提到的定時器解決方案。

相關問題