2017-09-24 377 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