How can I clear the Scanner buffer in Java?

clear buffer in java scanner
scanner reset java
problem with scanner in java
how to flush inputstream in java
how to clear string buffer in java
java scanner rewind
fflush(stdin) in java
how to clear bufferedreader in java

I have something like this:

    Scanner in=new Scanner(System.in);
    int rounds = 0;
    while (rounds < 1 || rounds > 3) {
        System.out.print("How many rounds? ");
        if (in.hasNextInt()) {
            rounds = in.nextInt();
        } else {
            System.out.println("Invalid input. Please try again.");
            System.out.println();
        }
        // Clear buffer
    }
    System.out.print(rounds+" rounds.");

How can I clear the buffer?

Edit: I tried the following, but it does not work for some reason:

while(in.hasNext())
    in.next();

You can't explicitly clear Scanner's buffer. Internally, it may clear the buffer after a token is read, but that's an implementation detail outside of the porgrammers' reach.

Java, I am making a bit more complex program in java and need help. I ask user Actually, you cannot empty or clean the Scanner buffer explicitly. The clear () method of java.nio.ByteBuffer Class is used to clear this buffer. The position is set to zero, the limit is set to the capacity, and the mark is discarded. Invoke this method before using a sequence of channel-read or put operations to fill this buffer.

Try this:

in.nextLine();

This advances the Scanner to the next line.

Java.util.Scanner.reset() Method, Resetting a scanner discards all of its explicit state information which may have been changed by invocations of useDelimiter(java.util.regex.Pattern), useLocale( � The code below show you how to clear a buffer using the clear() method call. The clear method call set the position in the buffer to 0 and limit to the capacity of the buffer. We usually call the clear() method after we read the entire content of a buffer and clear it for ready to be written again.

Use the following command:

in.nextLine();

right after

System.out.println("Invalid input. Please Try Again.");
System.out.println();

or after the following curly bracket (where your comment regarding it, is).

This command advances the scanner to the next line (when reading from a file or string, this simply reads the next line), thus essentially flushing it, in this case. It clears the buffer and readies the scanner for a new input. It can, preferably, be used for clearing the current buffer when a user has entered an invalid input (such as a letter when asked for a number).

Documentation of the method can be found here: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()

Hope this helps!

Buffer clear() methods in Java with Examples, The clear() method of java.nio.ByteBuffer Class is used to clear this buffer. The position is set to zero, the limit is set to the capacity, and the mark is discarded. Actually, you cannot empty or clean the Scanner buffer explicitly. So nextLine() is helpful here. How about taking the Scanner stream to the next line as soon as the arg2 integer input is taken?

This should fix it...

Scanner in=new Scanner(System.in);
    int rounds = 0;
    while (rounds < 1 || rounds > 3) {
        System.out.print("How many rounds? ");
        if (in.hasNextInt()) {
            rounds = in.nextInt();
        } else {
            System.out.println("Invalid input. Please try again.");
            in.next(); // -->important
            System.out.println();
        }
        // Clear buffer
    }
    System.out.print(rounds+" rounds.");

Scanner reset() method in Java with Examples, Pattern), useLocale(java.util.Locale), or useRadix(int). Syntax: public Scanner reset(). Return Value: This function returns this scanner which� [Java] How to clear buffer for Scanner input? Solved Hey guys, My problem is that when I prompt the user for entering the string for their choice it always resorts to my invalid input loop.

Other people have suggested using in.nextLine() to clear the buffer, which works for single-line input. As comments point out, however, sometimes System.in input can be multi-line.

You can instead create a new Scanner object where you want to clear the buffer if you are using System.in and not some other InputStream.

in = new Scanner(System.in);

If you do this, don't call in.close() first. Doing so will close System.in, and so you will get NoSuchElementExceptions on subsequent calls to in.nextInt(); System.in probably shouldn't be closed during your program.

(The above approach is specific to System.in. It might not be appropriate for other input streams.)

If you really need to close your Scanner object before creating a new one, this StackOverflow answer suggests creating an InputStream wrapper for System.in that has its own close() method that doesn't close the wrapped System.in stream. This is overkill for simple programs, though.

[Java] How to clear buffer for Scanner input? : learnprogramming, [Java] How to clear buffer for Scanner input? Solved. Hey guys, My problem is that when I prompt the� The java.util.Scanner.reset() method resets this scanner.Resetting a scanner discards all of its explicit state information which may have been changed by invocations of useDelimiter(java.util.regex.Pattern), useLocale(java.util.Locale), or useRadix(int). Declaration. Following is the declaration for java.util.Scanner.reset() method

How can I clear the Scanner buffer in Java?, I have something like this: Scanner in=new Scanner(System.in); int rounds = 0; while (rounds < 1 || rounds > 3) { System.out.print("How many� You can manually empty the Scanner before the player's turn like so (what (I think) you've been doing): while(in.hasNext()) in.next(); Or, you can close the scanner at the end of the player's turn and instantiate a new one at the beginning of the next turn (you can't reopen a closed Scanner ):

flush in java when using nextLine(), nextLine() to flush the buffer. 2. scan.skip(“[\\r\\n]+”); 3. use separate scanner for each name and address variables. Thus staying on the buffer. And description of nextLine() says. Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

Scanner Handout, Scanner class (so that you do not need to write java.util.Scanner) Attempt to read (and remove from buffer) a floating point decimal value of type double . java.util.Scanner class is a simple text scanner which can parse primitive types and strings. It internally uses regular expressions to read different types. Java.io.BufferedReader class reads text from a character-input stream, buffering characters so as to provide for the efficient reading of sequence of characters

Comments
  • what do you mean with "Clear buffer"? clear console (like cls dos command)?
  • I'm looking for something along the lines of: while(in.hasNext()) in.next();. For some reason that loop does not work.
  • Sometimes there are multiple lines entered, this only works for one line.
  • You would think hasNextLine (or hasNext) could be used to check if more input is available, but this doesn't work in Java. The hasNextLine/hasNext methods always return true for the keyboard (System.in). The only way I've found to clear all buffered data without blocking is to open a new scanner: in.close(); in = new Scanner(System.in);
  • @Georgie You would want to create the new Scanner without closing the old one. Closing the Scanner also closes the underlying readable (System.in in our case), so I get NoSuchElementExceptions on the next call to Scanner.next() if I close a System.in Scanner and create another one. If you really need to close the old one, this StackOverflow answer suggests you can get around this by creating a wrapper for System.in if you want to close it first.
  • @SansWit Works for me on Java 8 update 211, Windows 7. Maybe the behaviour is different in different JVM implementations/Java versions, which would be bad.
  • thank @Makoto, it works for me
  • Creating a NEW Scanner object was best suggestion! But, make sure that there is NO REFERENCE to the OLD scanner object so that it can be garbage collected.