简体   繁体   English

如何让Java等待用户输入

[英]How to get Java to wait for user Input

I am trying to make an IRC bot for my channel. 我正在尝试为我的频道制作一个IRC机器人。 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: 为了使主循环等待用户输入我添加循环的东西:

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

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 用户输入等待1.892秒
User input was: hello 用户输入是:你好
Please input a line 请输入一行
^D ^ d
System.in was closed; System.in已关闭; exiting 退出

So all you have to do is to use Scanner.nextLine() and your app will wait until the user has entered a newline. 因此,您所要做的就是使用Scanner.nextLine() ,您的应用将等到用户输入换行符。 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 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
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM