如何让 Java 等待用户输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30249324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get Java to wait for user Input
提问by Ulsting
I am trying to make an IRC bot for my channel. I would like the bot to be able to take commands from the console. In an attempt to make the main loop wait for the user to input something I added the loop:
我正在尝试为我的频道制作一个 IRC 机器人。我希望机器人能够从控制台接收命令。为了让主循环等待用户输入内容,我添加了循环:
while(!userInput.hasNext());
this did not seem to work. I have heard of BufferedReader but I have never used it and am not sure if this would be able to solve my problem.
这似乎不起作用。我听说过 BufferedReader 但我从未使用过它,我不确定这是否能够解决我的问题。
while(true) {
System.out.println("Ready for a new command sir.");
Scanner userInput = new Scanner(System.in);
while(!userInput.hasNext());
String input = "";
if (userInput.hasNext()) input = userInput.nextLine();
System.out.println("input is '" + input + "'");
if (!input.equals("")) {
//main code
}
userInput.close();
Thread.sleep(1000);
}
采纳答案by Raniz
There is no need for you to check for available input waiting and sleeping until there is since Scanner.nextLine()
will block until a line is available.
您无需检查等待和休眠的可用输入,直到有可用输入,因为Scanner.nextLine()
将阻塞,直到有一行可用。
Have a look at this example I wrote to demonstrate it:
看看我写的这个例子来演示它:
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
请输入一行
hello
等待用户输入 1.892s
用户输入是:hello
请输入一行
^D
System.in was closed; 退出
So all you have to do is to use Scanner.nextLine()
and your app will wait until the user has entered a newline. You also don't want to define your Scanner inside the loop and close it since you're going to use it again in the next iteration:
因此,您所要做的就是使用Scanner.nextLine()
,您的应用程序将等待用户输入换行符。您也不希望在循环内定义您的 Scanner 并关闭它,因为您将在下一次迭代中再次使用它:
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
}
}
}