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
Click For Summary
SUMMARY

The discussion focuses on using the Scanner class in Java to pause program execution until the user hits the return key. The user initially attempts to use kbd.next(), which requires actual input and does not respond to a simple return key press. The solution proposed involves utilizing the KeyListener class from the java.awt.event library to listen for the enter key, allowing the program to proceed without requiring additional input.

PREREQUISITES
  • Java programming fundamentals
  • Understanding of the Scanner class in Java
  • Familiarity with event-driven programming concepts
  • Knowledge of the java.awt.event package
NEXT STEPS
  • Explore the KeyListener interface in Java for handling keyboard events
  • Learn about event handling in Java Swing applications
  • Research alternative input methods in Java, such as using BufferedReader
  • Investigate asynchronous programming techniques in Java
USEFUL FOR

Java developers, particularly those working on console applications or GUI applications that require user input handling.

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.
 

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
Views
3K
  • · Replies 1 ·
Replies
1
Views
6K