我有以下java程序,该程序在循环时工作正常,但是我想运行执行,直到用户从键盘按下q键为止。
那么,在循环中打破循环时应放置什么条件?
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");
}
}
}
}
任何帮助都会很棒。谢谢。
我认为您无法在控制台应用程序中使用键盘,因为没有键盘侦听器定义。
尝试一个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"));
呢?
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");
}
}
}
}