如何在输出不断 运行 时获取输入

How to take input while an output is constantly running

所以我实际上是在尝试制作一个秒表应用程序,它的行为就像一个精确的秒表,所以它需要接受输入,所以我想做的是每当用户输入一些东西时循环就会中断......

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

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

我该怎么做?

你可以这样做:

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

如果您在 IDE 控制台中输入 运行,则必须输入内容并按 Enter。 不要使用 Scanner,因为它会阻塞并等待输入。