【问题标题】:Programm a loop that goes on until you enter something into console编写一个循环,直到您在控制台中输入内容
【发布时间】:2019-01-10 18:06:55
【问题描述】:

我正在尝试构建一个循环,当我在控制台中输入文本时执行一个特定的方法。 我想使用 java.util.Scanner 但是当我尝试使用 .hasNext() 来检查 if() 然后 .next() 来获取输入时,它会等到我输入一些东西而不是循环。

while(true) {
    main_loop();
}

private void main_loop() {
    do_other_things(); 
    if(sc.hasNext()){
        System.out.println("user entered " + sc.next());
    } else {
        System.out.println("user entered nothing");
    }
}

如何让它输出“用户没有输入任何内容”,直到我输入一些内容,以便它输出“用户输入的 [...]”,然后继续输出“用户没有输入任何内容”?

【问题讨论】:

  • 扫描仪就是这样工作的。它等待正确的输入,阻塞线程。我建议使用new Thread()
  • 您需要为此使用第二个线程,一个用于保持 while 循环

标签: java while-loop console java.util.scanner


【解决方案1】:

利用另一个线程:

public static void main(String[] args) {
    new Thread(() -> {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            if (scanner.hasNext()) {
                //... user has input
            }
            else {
                //... user does not have input
            }
    }).start();
    doSomethingElse();
}

【讨论】:

    【解决方案2】:

    您需要有一个单独的线程运行来等待输入(如果您希望在用户输入第二个字符串时触发它)一旦它处理了输入,再次安排可运行.

        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        Scanner scanner = new Scanner(System.in);
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                if (scanner.hasNext()) {
                    String st = scanner.next();
                    //do something now the user has inputted
                    System.out.printf("The user entered a string! (%s)", st);
    
                    //run the runnable to wait again
                    executorService.schedule(this, 0, TimeUnit.SECONDS);
                }
            }
        };
        executorService.schedule(runnable, 0, TimeUnit.SECONDS);
    }
    

    【讨论】:

    • executorService.schedule(this, 0, TimeUNit.SECONDS),与线程内部的while(true) 相比,这有什么好处? (真正的问题,我对 Java 的 Executor Service 还很陌生)
    • 你可以使用任何一种,这是个人喜好。但是,如果您想添加更多功能(例如“冷却”),这将提供更大的灵活性,您可以为此更改重新运行线程的延迟。另一方面,while (true) 更干净。有些人认为 while (true) 是不好的做法,虽然它确实有优点和缺点,但它是基于意见的。
    • 我刚刚在这里写了while(true)...里面有一个布尔值,用于触发它从里面离开。
    猜你喜欢
    • 2014-12-17
    • 1970-01-01
    • 1970-01-01
    • 2017-02-18
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 2011-09-08
    • 1970-01-01
    相关资源
    最近更新 更多