2013-03-26 85 views
0

如何清除Java中的標準輸入(term)?如何清除標準輸入(term)

歷史的一點點: 我寫了「反射」程序,算法很簡單:

wait a random amount of time 
print "press enter" 
read line 

的一點是,如果用戶錯誤地按下回車鍵時,它會被閱讀,所以測試將是錯誤的。我的目標是糾正這個錯誤。 要做到這一點,我想有這樣一個算法:

wait a random amount of time 
clear stdin 
print "press enter" 
read line 

但我不能找到一個方法來做到這一點。 This post似乎很有趣:available獲取剩餘字符的數量,skip將跳過它們。只能在紙上工作。如果通過按下多次輸入鍵強調應用,available方法返回

,可以從該輸入流中讀取(或跳過)的字節數的估計值而不阻擋

因此,有時候,返回值是錯誤的,至少有一個回車符保留在緩衝區中,錯誤仍然存​​在。

This solution可以做的伎倆,但它是平臺依賴,我不想成爲。此外,從Java調用系統例程是一個不錯的主意。

要恢復,我想清除我的程序的標準輸入,但我不想關閉它,也不會阻止我的程序等待用戶輸入。對我來說,這似乎是一個非常基本的問題,如果答案很明顯!

+0

除非您想要假設VT100代碼,否則您沒有太多選項。但爲什麼在控制檯中呢?編寫一個非常小的Swing應用程序 - 解決問題。 – 2013-03-27 00:00:58

回答

1

我沒有回答「清除stdin」。我認爲這是特定操作系統,這可能甚至不值得嘗試。

但是要解決您的問題,您可以使用java.util.Timer在隨機時間提示用戶。這將在一個單獨的線程中運行。當用戶最終按下輸入時,檢查他/她是否被提示。

下面的代碼示例將在5秒後打印「Press enter」。主線程立即阻止等待用戶輸入,如果輸入過早按下,則會這樣說,因爲布爾開關尚未打開。

*注意:TimerTest是I所提供的類的名稱。隨意將其更改爲任何類名

static boolean userPrompted = false; 

public static void main(String[] args) throws IOException { 

    // Setup a 5 second timer that prompts the user and switch the userPrompted flag to true 
    // This will run in a separate thread 
    Timer timer = new Timer(false); 
    timer.schedule(new TimerTask() { 
     @Override 
     public void run() { 
      System.out.println("Press enter"); 
      synchronized(TimerTest.class) { 
       userPrompted = true; 
      } 
     } 
    }, 5000); 

    // Blocks waiting for user input 
    System.out.println("Get ready.. press enter as soon as you're prompted.."); 
    String input = new BufferedReader(new InputStreamReader(System.in)).readLine(); 

    // Check if user has been prompted 
    synchronized (TimerTest.class) { 
     if(!userPrompted) System.out.println("You pressed enter before prompted"); 
     else System.out.println("You pressed enter after prompted"); 
    } 

} 
+0

感謝您的回答。是的,應該做的工作,我想我會做到這一點。然而,正如你所說,這不是一個「清晰的終端」的答案,所以我會在等待其他選項,然後再驗證你的答案。再次感謝。 – FaustXVI 2013-03-27 09:51:28