Java Using Scanner in Java to await user hitting return key

  • Thread starter Thread starter mr.hood
  • Start date Start date
  • Tags Tags
    Java Scanner
Click For Summary
To pause a Java program until the user hits the return key, using the Scanner class alone is insufficient, as it requires actual input rather than just a key press. Instead, a KeyListener from the java.awt.event library is recommended. This approach allows the program to listen for the Enter key event, enabling it to proceed without waiting for additional input. Implementing a listener can effectively manage user interactions in a more flexible manner than the Scanner class.
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:
Technology 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.
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

  • · Replies 1 ·
Replies
1
Views
7K
  • · Replies 2 ·
Replies
2
Views
2K
Replies
4
Views
2K
Replies
3
Views
3K
Replies
1
Views
8K
  • · Replies 5 ·
Replies
5
Views
3K
Replies
1
Views
2K
  • · Replies 7 ·
Replies
7
Views
4K
  • · Replies 1 ·
Replies
1
Views
6K
Replies
1
Views
3K