2012-02-19 94 views
1

我在Windows 7上編寫Java,並希望能夠使用鍵盤的輸入,我只能假設它是標準輸入。從鍵盤獲取輸入而不暫停程序

我試過使用BufferedInputSystem.inScanner,但它們都需要程序暫停並等待行結束或返回!無論如何只是收集和記錄數據,因爲它使用,而不必等待回報?

+2

您可以創建一個新線程,並在此新線程中請求輸入,同時在主線程中執行其他操作。 – florian 2012-02-19 11:44:25

+0

*「不必等待返回*我(作爲用戶)在我很好並準備好應用程序時點擊'返回'對數據做些什麼事情以前,應用程序做什麼用途那個時候?你想要提供什麼樣的應用程序功能? – 2012-02-19 11:59:41

+0

我想我只是理解你說的問題安德魯。我不認爲你可以在控制檯上做你想做的事 – florian 2012-02-19 12:15:20

回答

1

這裏是一個快速的解決方案:

public static void main(String[] args) { 

    Thread inputThread = new Thread(new Runnable() { 
     @Override 
     public void run() { 

      Scanner scan = new Scanner(System.in); 
      String input = ""; 
      while (true) { 
       System.out.println("Type something: "); 
       input = scan.nextLine(); 
       System.out.println("Input: "+input); 
      } 
     } 
    }); 

    inputThread.start(); 

    while (true) { 

     System.out.println(""); 
     System.out.println("test"); 

     try { 
      Thread.sleep(1000); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
    } 

} 

主線程打印 「測試」 每一秒。 inputThread要求用戶鍵入內容然後打印他寫的內容。這只是一種「可視化」解決方案,當然用戶打字時你肯定不想打印某些東西。