加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

如何让Java等待用户输入

发布时间:2020-12-15 04:45:52 所属栏目:Java 来源:网络整理
导读:我正在尝试为我的频道制作一个IRC机器人.我希望机器人能够从控制台获取命令.为了使主循环等待用户输入我添加循环的东西: while(!userInput.hasNext()); 这似乎不起作用.我听说过BufferedReader,但我从未使用它,也不确定这是否能够解决我的问题. while(true)
我正在尝试为我的频道制作一个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);
    }

解决方法

您无需检查可用的输入等待和休眠,直到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
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读