如何让Java等待用户输入

15

我正在尝试为我的频道制作一个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);
    }
1个回答

24

你不需要检查是否有可用的输入,并等待直到有输入,因为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");
        }
    }
}

请输入一行文字
你好
等待用户输入1.892秒
用户输入为: 你好
请输入一行文字
^D
System.in已关闭; 程序退出

所以你只需要使用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
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接