I'm trying to build a Command Line Interface with this functionality: if the user takes more than 15 seconds to insert an input (an Integer in this case), the function makes a default choice (0). The code below is what I wrote so far and it works properly.
The problem is that I wanna add a new functionality: if the user writes a wrong number (<0 or >range) the console should print something like ("Wrong choice, you have to pick an integer between 0 - "+ range);
However, while the console prints the message, the timer should still be running and end this loop after 15 seconds, in case the user keeps inserting wrong numbers. In case the user gets eventually a correct number, it should break the loop immediately.
This is my code, but I don't have clear ideas on how to add the functionality because I'm relatively new to Future,Callable and Executor functionalities. If anyone has more experience on it I would be glad to learn!
private int getChoiceWithTimeout(int range){
Callable<Integer> k = () -> new Scanner(System.in).nextInt();
Long start= System.currentTimeMillis();
int choice=0;
ExecutorService l = Executors.newFixedThreadPool(1); ;
Future<Integer> g;
System.out.println("Enter your choice in 15 seconds :");
g= l.submit(k);
while(System.currentTimeMillis()-start<15*1000 && !g.isDone()){
// Wait for future
}
if(g.isDone()){
try {
choice=g.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
g.cancel(true);
return choice;
}