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
Asked
Active
Viewed 5,337 times
4
-
Use getCharacters().toString(); instead. Check this: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/TextField.html#getCharacters-- – Petro Gordiyevich May 18 '17 at 03:27
-
@PetroGordiyevich What are you talking about? – shmosel May 18 '17 at 03:29
-
sorry, answered to wrong question. – Petro Gordiyevich May 18 '17 at 03:30
-
You need to show us your code and what you have already tried. – Enstage May 18 '17 at 04:15
-
@Enstage I honestly have no idea what to even try. – Jerry Chen May 18 '17 at 18:37
1 Answers
2
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
Community
- 1
- 1
fileyfood500
- 1,023
- 11
- 24