2

I am working on a card game and I need to get the user input from the console. To do so, I am using the class Scanner, more specifically the method nextInt(). But, if the user does not provide an option within 60 seconds, the system should be able to select one randomly. I would like to know if there is a way to "cancel" the previously made call to the method nextInt() and use the one generated by Random.nextInt() instead.

The code responsible for it is:

System.out.print("Enter the number of your choice");
option = scanner.nextInt();

I have read about ways to do it using GUI, but in my case, I am not planning on having one.

Thanks

EDIT1:

I have been doing some research on this and I believe that monitoring the keyboard for the pressed keys would solve my problem, I am now working on finding out how to monitor the keyboard and get the pressed keys. Can anyone help me with that?

fernandonos
  • 173
  • 1
  • 4
  • 15
  • An idea perhpaps is not the best you can use a `Timer` that executes in another thread , sleep that thread x seconds, use a volatile variable with default value if don't change default value then apply your random value. – nachokk Sep 22 '13 at 02:43

2 Answers2

0

Do you really want a time out or just a way to say "computer choose"? The usual way around this is to have the user enter a sentinel value, this value has not a valid answer (like 0 or -1 etc).

If you want to implement a timeout instead, it is much more complicated and probably involves multithreading. I would advise you to read this question: Is it possible to read from a InputStream with a timeout?

Community
  • 1
  • 1
dkatzel
  • 31,188
  • 3
  • 63
  • 67
0

I am not sure that this can even be done without a GUI. If it could be done, the code would be devilishly complicated. If I figure out a way to do this, I'll post it.

tbodt
  • 16,609
  • 6
  • 58
  • 83