I am programming using Java.
I am trying write code which can recognize if the user presses the enter key in a console based program.
How can I do this using java. I have been told that this can be done using either Scanner or, buffered input reader. I do not understand(or know how to use) buffered input reader.
I tried to do do this using scanner but after pressing enter twice the program terminates, and it doesn't work
Scanner readinput = new Scanner(System.in);
String enterkey = "Hola";
System.out.print(enterkey);
enterkey = readinput.nextLine();
System.out.print(enterkey);
if(enterkey == ""){
System.out.println("It works!");
Thanks
-- edit --
the following code works using the equals
method for the string instead of ==
Scanner readinput = new Scanner(System.in);
String enterkey = "Hola";
System.out.print(enterkey);
enterkey = readinput.nextLine();
System.out.print(enterkey);
if(enterkey.equals("")){
System.out.println("It works!");
how can this be done, and what are the pros to doing this using the buffered input reader?
This works using java.util.Scanner and will take multiple "enter" keystrokes:
To break it down:
These lines initialize a new
Scanner
that is reading from the standard input stream (the keyboard) and reads a single line from it.While the scanner is still returning non-null data, print each line to the screen.
If the "enter" (or return, or whatever) key is supplied by the input, the
nextLine()
method will return an empty string; by checking to see if the string is empty, we can determine whether that key was pressed. Here the text Read Enter Key is printed, but you could perform whatever action you want here.Finally, after printing the content and/or doing something when the "enter" key is pressed, we check to see if the scanner has another line; for the standard input stream, this method will "block" until either the stream is closed, the execution of the program ends, or further input is supplied.
This code works fine