如何清除标准输入(术语)

时间:2013-03-26 23:53:25

标签: java stdin

如何清除Java中的标准输入(术语)?

一点历史: 我正在写一个“反射”程序,算法非常简单:

wait a random amount of time
print "press enter"
read line

关键是,如果用户误按了回车键,它将被读取,因此测试将是错误的。我的目标是纠正这个错误。 为此,我想要一个这样的算法:

wait a random amount of time
clear stdin
print "press enter"
read line

但我找不到办法做到这一点。 This post似乎很有趣:available获取剩余字符数,skip将跳过它们。只在纸上工作。如果您通过多次按Enter键来强调应用程序,available方法将返回

  
    

估计可以从此输入流中无阻塞地读取(或跳过)的字节数

  

所以,有时,返回值是错误的,至少有一个回车符保留在缓冲区中,并且错误仍在此处。

This solution可以做到这一点,但它依赖于平台,我不想这样做。此外,从Java调用系统例程是一个非常糟糕的主意。

要恢复,我想清除程序的标准输入,但我不想关闭它,也不想阻止我的程序等待用户输入。如果答案显而易见,对我来说这似乎是一个非常基本的问题!

1 个答案:

答案 0 :(得分:1)

我没有回答“清除stdin”。我认为这是特定于操作系统的,甚至可能都不值得尝试。

但是要解决您的问题,您可以使用java.util.Timer在某个随机时间提示用户。这将在一个单独的线程中运行。当您的用户最后按Enter键时,请检查他/她是否已被提示。

下面的代码示例将在5秒后打印“按下输入”。主线程立即阻止等待用户输入,如果过早按下它会说明因为布尔开关尚未打开

*注意:TimerTest是我操作的类的名称。随意将其更改为您的班级名称

static boolean userPrompted = false;

public static void main(String[] args) throws IOException {

    // Setup a 5 second timer that prompts the user and switch the userPrompted flag to true
    // This will run in a separate thread
    Timer timer = new Timer(false);
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            System.out.println("Press enter");
            synchronized(TimerTest.class) {
                userPrompted = true;
            }
        }
    }, 5000);

    // Blocks waiting for user input
    System.out.println("Get ready.. press enter as soon as you're prompted..");
    String input = new BufferedReader(new InputStreamReader(System.in)).readLine();

    // Check if user has been prompted
    synchronized (TimerTest.class) {
        if(!userPrompted) System.out.println("You pressed enter before prompted");
        else System.out.println("You pressed enter after prompted");
    }

}