DEV Community

Darsh
Darsh

Posted on

How to detect enter key from the keyboard in java

I'm stuck.
I want the user to press enter key to proceed, but I don't know how to detect enter key press.
please help.

Top comments (1)

Collapse
 
cicirello profile image
Vincent A. Cicirello • Edited

I'm assuming you mean in a console application.... You can use a Scanner. The hasNextLine method will return true if they enter anything. You can follow that with a call to nextLine which will remove that line from the input stream and return it to you. If you literally only want to proceed if they pressed only the enter key and nothing else then you can check if the string returned is the empty string.

Scanner in = new Scanner(System.in);
System.out.println("Press enter to continue.");
if (in.hasNextLine()) {
  String s = in.nextLine();
  // s will be whatever they entered without new line character.
  // Even if you don't need to know what they entered, 
  // call nextLine or else it will continue to sit on input stream
  // and lead to subsequent calls to hasNextLine
  // to evaluate to true before they enter anything else.
}

// You will only get here after they enter something.
System.out.println("Yay! You pressed enter.");
Enter fullscreen mode Exit fullscreen mode

Note that the hasNextLine will never return false if Scanner reading from System.in. It will wait for input and then return true.