How to stop waiting for user input?

懵懂的女人 提交于 2019-12-05 10:08:29

You can check for System.in.available() > 0 to see if there is a line to read. Only if this returns true call the sc.nextLine() to actually receive the input.

An example:

Scanner sc = new Scanner(System.in);

long sTime = System.currentTimeMillis();
while (System.currentTimeMillis() - sTime < 5000)
{
    if (System.in.available() > 0)
    {
        System.out.println(sc.nextLine());
    }
}

sc.close();

This reads from the console for 5 seconds if there is something to read and just prints it out again. Note: When actually using this you would probably throw a sleep in the loop to not hug to many system resources.

Please note that this is a can work solution: available() tends to be an unreliable method that does some estimation and can be in the wrong. I would probably not rely on it in a time-critical system, etc.

Also to further expand, this approach relies on the console to work the way most consoles work (in other words: All consoles that I know of): Only when the user enters a newline (by e.g. pressing enter) the line is actually given to System.in to process. Else available() would already return true when only one character gets typed.

have you tried to use close, you can check if the input is "" when the time is up and close it, might help;

if(scanner!=null)
{
    scanner.close();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!