Using Scanner in Java to await user hitting return key

  • Context: Java 
  • Thread starter Thread starter mr.hood
  • Start date Start date
  • Tags Tags
    Java Scanner
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
1 reply · 9K views
mr.hood
Messages
6
Reaction score
0
Hi all,

I've been trying to figure out how I can use the Scanner class in Java to pause my program and wait for the user to hit the return key. What I have now looks like this:

Scanner kbd = new Scanner(System.in);
kbd.next();
...

The thing is, the rest of my program won't run unless there is actually some kind of input (i.e. just hitting the return key without any input just makes the program keep waiting for input). Is there a way I can get around this?
 
Last edited:
Physics news on Phys.org
I don't think that scanner has that functionality. What scanner.next() does is it was for user input and returns the input. It does not accept null characters.

What your looking for is some type of listener. Take a look at the KeyListener class from java.awt.event.* libary. Just perform some wait function and listen for the enter key.