2017-09-24 376 views
0

我有下面這個java程序,它在沒有while循環的情況下工作正常,但我想運行執行,直到用戶從鍵盤按下Q鍵。Java:按下「Q」鍵後終止while循環

那麼,什麼樣的條件應該放在while循環打破循環?

import java.awt.event.KeyEvent; 
import java.util.Scanner; 
import static javafx.scene.input.KeyCode.Q; 

public class BinaryToDecimal { 
    public static void main(String[] args) { 
     Scanner in = new Scanner(System.in);   
     while(kbhit() != Q){ 
      System.out.print("Input first binary number: "); 
      try{   
       String n = in.nextLine(); 
       System.out.println(Integer.parseInt(n,2)); 
      } 
      catch(Exception e){ 
       System.out.println("Not a binary number"); 
      } 
     } 
    } 
} 

任何幫助將是偉大的。 謝謝。

+0

我知道的kbhit()在C語言中,但不知道在java中 –

+0

問題不清楚,直到你證明方法 –

+0

那麼究竟什麼是你的問題?你想知道,你如何閱讀鍵盤輸入? – dunni

回答

3

我不認爲你可以在控制檯應用程序中使用KeyEvent,因爲沒有定義鍵盤監聽器。

嘗試一個do-while循環來觀察字母q的輸入。你應該比較字符串使用等於方法

Scanner in = new Scanner(System.in);   
    String n; 
    System.out.print("Input first binary number: "); 
    do { 
     try{   
      n = in.nextLine(); 
      // break early 
      if (n.equalsIgnoreCase("q")) break; 
      System.out.println(Integer.parseInt(n,2)); 
     } 
     catch(Exception e){ 
      System.out.println("Not a binary number"); 
     } 
     // Prompt again 
     System.out.print("Input binary number: "); 
    } while(!n.equalsIgnoreCase("q")); 
+0

無論我們在try塊中放置「if」語句,輸出看起來都一樣。讓我知道它是否可以減少不必要的開銷? –

+0

不確定你的意思。顯然,你想防止解析字母q作爲整數 –

+0

在try塊中,「if(n.equalsIgnoreCase(」q「))break;」它會減少執行時間還是縮短執行時間?如果用戶的輸入是開頭的「q」。 –

0

這是怎麼回事?

public class BinaryToDecimal { 
    public static void main(String[] args) { 
     System.out.print("Input first binary number: "); 
     Scanner in = new Scanner(System.in); 
     String line = in.nextLine(); 
     while(!"q".equalsIgnoreCase(line.trim())){ 
      try{ 
       System.out.println(Integer.parseInt(line,2)); 
       System.out.print("Input next binary number: ");   
       line = in.nextLine(); 
      } 
      catch(Exception e){ 
       System.out.println("Not a binary number"); 
      } 
     } 
    } 
} 
+0

那麼,您在「輸入第一個二進制數」之前提示輸入,這可能不是明顯的 –

+0

感謝您指出!固定。 – P3trur0