Java scanner entry key
I use Java programming
How do I use java to do this I was told that this could be done using a scanner or a buffered input reader I don't understand (or know how to use) buffered input readers
I tried to use the scanner to do this, but after pressing the program twice to terminate, entering it did not 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!");
thank you
– edit – the following code uses the equals method for strings 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 do you do this and what are the benefits of using a buffered input reader?
Solution
This can be done using Java util. Scanner and performs multiple "input" keystrokes:
Scanner scanner = new Scanner(system.in); String readString = scanner.nextLine(); while(readString!=null) { System.out.println(readString); if (readString.isEmpty()) { System.out.println("Read Enter Key."); } if (scanner.hasNextLine()) { readString = scanner.nextLine(); } else { readString = null; } }
Break it:
Scanner scanner = new Scanner(system.in); String readString = scanner.nextLine();
These lines initialize the new scanner read from the standard input stream and read a line from it
while(readString!=null) { System.out.println(readString);
When the scanner still returns non empty data, print each line to the screen
if (readString.isEmpty()) { System.out.println("Read Enter Key."); }
If the input provides an "input" (or return) key, the nextline() method returns an empty string; By checking whether the string is empty, we can determine whether the key is pressed The text read enter key is printed here, but you can do anything you want here
if (scanner.hasNextLine()) { readString = scanner.nextLine(); } else { readString = null; }
Finally, after pressing the "enter" key to print content and / or do something, we check whether the scanner has another line; For standard input streams, the method will "block" until the stream closes, program execution ends, or further input