当用户没有从键盘输入任何内容时,如何在我们使用扫描仪 readLine() 时跳过控制?

How to skip control when we are using scanner readLine() when user is nothing entered from keyboard?

我的代码是:

System.out.print("press key Y or N to run the test");
Scanner sc = new Scanner(System.in);
String input = null;
input = sc.nextLine();

你无能为力。 nextLine() 等待用户按下键盘上的 "Enter";它将永远阻塞,直到发生这种情况。

如果您真的希望事情发生 "automatically",您将需要一个更复杂的解决方案;例如,您可以在单独的线程中等待用户输入;如果在给定的时间后没有输入,您的另一个线程可以开始执行 "whatever" "automatically".

请告诉用户在输入后点击 return 并检查空行,如下所示:

if("".equals(input)){ //skip control
}
else{   //do something on input
}