Set Time Limit on User Input (Scanner) Java

2019-01-29 12:39发布

问题:

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:

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