0
\$\begingroup\$

I'm contemplating how to read an int using Scanner.nextInt(), and at the same time ignore the rest of the line or flush the input buffer to be ready for inputting the next number. Typical usage would be to read a number where the user is likely to add units or similar after the number, and I want the scanner to be cleared out before I output a new message and ready for the next number.

In the following code I firstly use Scanner.nextLine() to read rest of line, and in the second I attempted to use the Scanner.hasNext() to detect if anything was present. But it originally failed, so to get it to work I had to add a bug-fix related to writing the text "quit". The third read is just to finish off with a final read of an integer.

import java.util.Scanner;

class Main {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("1) Enter an integer (with some junk like units): ");
        int myFirstInt = scanner.nextInt();
        // Ignore rest of line
        scanner.nextLine();

        System.out.print("2) Enter an integer (and some junk afterwards): ");
        int mySecondInt = scanner.nextInt();

        // Clear out scanner before next read...
        String line;                    // Fix to avoid endless loop
        while (scanner.hasNext()) {
            line = scanner.next();
            if (line.equals("quit")) {  // Fix to avoid endless loop
                break;                  // Fix to avoid endless loop
            }                           // Fix to avoid endless loop
        }

        System.out.print("3) Enter the third integer: ");
        int myThirdInt = scanner.nextInt();

        System.out.printf("\nFirst: %d, Second: %d, Third: %d\n",
                          myFirstInt, mySecondInt, myThirdInt);
    }
}

A typical run with this code:

1) Enter an integer (with some junk like units):  123 kg
2) Enter an integer (and some junk afterwards):  45 stones 5 pound
 quit
3) Enter the third integer:  238

First: 123, Second: 45, Third: 238

The code now works (with the need for entering "quit" at the second prompt), but I'm wondering whether there is a safer or better method for clearing out the scanner, so I can get it ready for reading the next input. Hopefully with the out endless loop fix. The output is as expected.

\$\endgroup\$
  • \$\begingroup\$ I don't understand what is your desired behaviour, what is your workaround, or why you would look for "quit" before continuing to the third prompt. \$\endgroup\$ – 200_success Feb 29 '16 at 23:10
  • \$\begingroup\$ @200_success, I was thinking that I could do while (scanner.hasNext()) {scanner.next(); } to flush the input buffer, but that turned in to an endless loop, so to give myself a way out I added the lines with // Fix .... It was meant as alternative to just using a single scanner.nextLine(). \$\endgroup\$ – holroy Feb 29 '16 at 23:13
1
\$\begingroup\$

In order to remove the junk after the integer, you can make use of Scanner.skip(Pattern pattern). It allows you to skip over any set of characters that match a pattern:

scanner.skip(".*");

This method call will cause the Scanner to skip over any characters that match the pattern ".*" . The period character in a regular expression matches any single character. The repetition character * causes matching zero or more of the previous character. So the pattern .* will match zero or more of any characters. Thus, it will skip over any characters currently on the stream. So now our code will look like:

    int myFirstInt = scanner.nextInt();
    // Ignore rest of line
    scanner.skip(".*");

    System.out.print("2) Enter an integer (and some junk afterwards): ");
    int mySecondInt = scanner.nextInt();
    scanner.skip(".*");
    System.out.print("3) Enter the third integer: ");
    int myThirdInt = scanner.nextInt();

    System.out.printf("\nFirst: %d, Second: %d, Third: %d\n",
                      myFirstInt, mySecondInt, myThirdInt);

It is a simple way to flush the stream so that it is clear of bad characters, and ready to be reused!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.