2011-10-26 19 views
0

我試圖實現用戶必須在測驗中回答問題的時間限制。雖然我發現了很多怯懦者,但我不知道如何將它們拼湊在一起。Java:在測驗中使用計時器

我希望用戶有15秒的時間來回答問題。如果他們及時回答,它會檢查答案是否正確,然後詢問他們是否想繼續下一個問題。

如果用戶在15秒內沒有迴應,那麼應該說答案是不正確的,並讓他們選擇移動到下一個問題。

這是我到目前爲止。

for(int i=0; i<quiz.getQuizQuestions().size(); i++){ 

     super.getQuestion(i); 

     //While timer is less than 15 seconds 

     getResponse(i, questionStart); 

     //If time has run out output "You have run out of time" 

     super.nextQuestion(); 


} 

這可能是值得了解的:

super.getQuestion(我)只是打印所提出的問題

GETRESPONSE()正在等待鍵盤輸入。如果輸入內容,則檢查用戶是否正確。

super.nextQuestion()詢問用戶是他們要移動到下一個問題

在此先感謝

編輯:這也將是驚人的,如果它是很容易實現的是倒計時計數器從15轉換成GUI時從15。

+0

作業,有什麼機會?沒關係,如果是這樣的話,只需標記即可。 –

回答

1

使用ExecutorService和Future來確保我們讀取一行或中斷它。代碼比我預期的稍長...讓我知道如果有什麼不清楚:

import java.util.concurrent.*; 
import java.io.*;  

public class Test { 
    public static void main(String[] args) throws java.io.IOException { 
     Question q = new Question(); 
     System.out.println("You have 5 seconds: " + q.toString()); 

     String userAnswer = null;  
     ExecutorService ex = Executors.newSingleThreadExecutor(); 
     try { 
      Future<String> result = ex.submit(new GetInputLineCallable()); 
      try { 
      userAnswer = result.get(5, TimeUnit.SECONDS); 
      if (Integer.valueOf(userAnswer) == q.getAnswer()){ 
       System.out.println("good!"); 
      } 
      else{ 
       System.out.println("Incorrect!"); 
      } 

      } catch (ExecutionException e) { 
      e.getCause().printStackTrace(); 
      } catch (TimeoutException e){ 
      System.out.println("too late!"); 
      return; 
      } catch (InterruptedException e){ 
      System.out.println("interrupted?"); 
      e.getCause().printStackTrace(); 
      } 

     } finally { 
      ex.shutdownNow(); 
     } 
    } 
} 



class GetInputLineCallable implements Callable<String> { 
    public String call() throws IOException { 
    BufferedReader inp = new BufferedReader(new InputStreamReader(System.in)); 
    String input = ""; 
    while ("".equals(input)) { 
     try { 
     while (!inp.ready()) { 
      Thread.sleep(100); 
     } 
     input = inp.readLine(); 
     } catch (InterruptedException e) { 
     return null; 
     } 
    } 
    return input; 
    } 
} 




class Question{ 
    int p1, p2; 
    public Question(){ 
    p1 = 2; 
    p2 = 3; 
    } 
    public String toString(){ 
    return String.format("%d + %d = ?", p1, p2); 
    } 
    public int getAnswer(){ 
    return p1+p2; 
    } 
} 
0
long startTime = System.currentTimeMillis(); 

    while(System.currentTimeMillis() - startTime < 15000){ 
     if(userAnswered){ 
      break; // if there is an answer we stop waiting 
     } 
     Thread.sleep(1000); // otherwise we wait 1 sec before checking again 
    } 

    if(userAnswered){ 
     goToNextQuestion(); 
    } 
    else { 
     handleTimeOut(); 
    } 
+0

它阻止用戶? – Serhiy

+0

只需要注意OP需要在另一個線程中使用它,否則用戶將無法鍵入任何響應,因爲您的程序處於睡眠狀態直到超時。 –