您无需检查可用的输入等待和休眠,直到Scanner.nextLine()将阻塞,直到有一条线可用.
看看我写的这个例子来演示它:
public class ScannerTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
while (true) {
System.out.println("Please input a line");
long then = System.currentTimeMillis();
String line = scanner.nextLine();
long now = System.currentTimeMillis();
System.out.printf("Waited %.3fs for user input%n", (now - then) / 1000d);
System.out.printf("User input was: %s%n", line);
}
} catch(IllegalStateException | NoSuchElementException e) {
// System.in has been closed
System.out.println("System.in was closed; exiting");
}
}
}
Please input a line
hello
Waited 1.892s for user input
User input was: hello
Please input a line
^D
System.in was closed; exiting
因此,您所要做的就是使用Scanner.nextLine(),您的应用将等到用户输入换行符.你也不想在循环中定义你的扫描仪并关闭它,因为你将在下一次迭代中再次使用它:
Scanner userInput = new Scanner(System.in);
while(true) {
System.out.println("Ready for a new command sir.");
String input = userInput.nextLine();
System.out.println("input is '" + input + "'");
if (!input.isEmpty()) {
// Handle input
}
}
}