gpt4 book ai didi

java - 如何让Java等待用户输入

转载 作者:搜寻专家 更新时间:2023-11-01 01:16:30 25 4
gpt4 key购买 nike

我正在尝试为我的 channel 制作一个 IRC 机器人。我希望机器人能够从控制台接收命令。为了让主循环等待用户输入内容,我添加了循环:

while(!userInput.hasNext());

这似乎没有用。我听说过 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);
}

最佳答案

您无需检查是否有可用的输入等待和 hibernate 直到有,因为 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 并关闭它,因为您将在下一次迭代中再次使用它:

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
}
}
}

关于java - 如何让Java等待用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30249324/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com