Set Time Limit on User Input (Scanner) Java

2019-01-29 12:46发布

So I'm trying to read user input using the Scanner class. Is there a simple way to make it so that after 10 seconds it moves onto the next block of code? Thanks

1条回答
欢心
2楼-- · 2019-01-29 13:43

You can use Timer and TimerTask. TimerTask will allow you to run a task after a certain amount of time, in this case you can use this task to stop waiting for the user.

import java.util.Timer;
import java.util.TimerTask;

...

TimerTask task = new TimerTask()
{
    public void run()
    {
        if( str.equals("") )
        {
            System.out.println( "you input nothing. exit..." );
            System.exit( 0 );
        }
    }    
};

...

Timer timer = new Timer();

timer.schedule( task, 10*1000 );

Scanner sc = new Scanner(System.in);
String in = sc.readLine();

timer.cancel();

So if the user doesn't respond within 10 seconds here, the timer will quit reading input. I stole/adapted this response from this initial post: Time limit for an input

查看更多
登录 后发表回答