[java] Java using scanner enter key pressed

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 question is related to java input console java.util.scanner bufferedreader

The answer is


This works using java.util.Scanner and will take multiple "enter" 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;
        }
    }

To break it down:

Scanner scanner = new Scanner(System.in);
String readString = scanner.nextLine();

These lines initialize a new Scanner that is reading from the standard input stream (the keyboard) and reads a single line from it.

    while(readString!=null) {
        System.out.println(readString);

While the scanner is still returning non-null data, print each line to the screen.

        if (readString.isEmpty()) {
            System.out.println("Read Enter Key.");
        }

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.

        if (scanner.hasNextLine()) {
            readString = scanner.nextLine();
        } else {
            readString = null;
        }

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.


Scanner scan = new Scanner(System.in);
        int i = scan.nextInt();
        Double d = scan.nextDouble();


        String newStr = "";
        Scanner charScanner = new Scanner( System.in ).useDelimiter( "(\\b|\\B)" ) ;
        while( charScanner.hasNext() ) { 
            String  c = charScanner.next();

            if (c.equalsIgnoreCase("\r")) {
                break;
            }
            else {
                newStr += c;    
            }
        }

        System.out.println("String: " + newStr);
        System.out.println("Int: " + i);
        System.out.println("Double: " + d);

This code works fine


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to input

Angular 4 - get input value React - clearing an input value after form submit Min and max value of input in angular4 application Disable Button in Angular 2 Angular2 - Input Field To Accept Only Numbers How to validate white spaces/empty spaces? [Angular 2] Can't bind to 'ngModel' since it isn't a known property of 'input' Mask for an Input to allow phone numbers? File upload from <input type="file"> Why does the html input with type "number" allow the letter 'e' to be entered in the field?

Examples related to console

Error in MySQL when setting default value for DATE or DATETIME Where can I read the Console output in Visual Studio 2015 Chrome - ERR_CACHE_MISS Swift: print() vs println() vs NSLog() Datatables: Cannot read property 'mData' of undefined How do I write to the console from a Laravel Controller? Cannot read property 'push' of undefined when combining arrays Very simple log4j2 XML configuration file using Console and File appender Console.log not working at all Chrome: console.log, console.debug are not working

Examples related to java.util.scanner

How do I use a delimiter with Scanner.useDelimiter in Java? How to read multiple Integer values from a single line of input in Java? What's the difference between next() and nextLine() methods from Scanner class? Read line with Scanner Rock, Paper, Scissors Game Java Java using scanner enter key pressed Scanner is never closed how to insert a new line character in a string to PrintStream then use a scanner to re-read the file Exception in thread "main" java.util.NoSuchElementException Using a scanner to accept String input and storing in a String Array

Examples related to bufferedreader

Java using scanner enter key pressed How to read until end of file (EOF) using BufferedReader in Java? How to use BufferedReader in Java Using BufferedReader.readLine() in a while loop properly Convert InputStream to BufferedReader Android Reading from an Input stream efficiently Scanner vs. BufferedReader Do I need to close() both FileReader and BufferedReader?