如何在一个输出不断运行的情况下接受输入?

问题描述 投票:1回答:1

所以,我实际上是想做一个像秒表一样的应用程序,它需要接受输入,所以我想做的是每当用户输入一些东西时,循环就会中断......。

这是我的代码............。

public class Stop {
    public static void stopwatch() {
        Scanner sc = new Scanner(System.in);       

        System.out.println("Enter anything when you want to stop");
        for(double i = 0; true; i+=0.5) {
            System.out.println(i);

            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } 

        }        
    }
}

所以,我想接受一个输入,但它应该是可选的,无论用户是否输入,如果他输入,循环就会中断,否则就会继续......。

我的输出应该是这样的

Enter anything when you want to stop
0.0
0.5
1.0
1.5
stop
You stopped

我该怎么做呢?

java loops break
1个回答
1
投票

你可以这样做。

    public static void stopwatch() {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter anything when you want to stop");

        for (double i = 0; true; i += 0.5) {
            try {
                if (!br.ready()) {
                    System.out.println(i);
                    Thread.sleep(500);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

你必须输入一些东西,然后按Enter键 如果你是在IDE控制台运行的话,不要用Scanner,因为它会阻塞并等待输入。

© www.soinside.com 2019 - 2024. All rights reserved.