Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I clear the Scanner buffer in Java?

Tags:

java

io

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(); 
like image 876
Leo Jiang Avatar asked May 15 '12 15:05

Leo Jiang


People also ask

How do I clear my Scanner buffer?

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);

What is clearing the buffer in Java?

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.

Can you reset a Scanner Java?

The reset() method of java. util. Scanner class resets this scanner. On resetting a scanner, it discards all of its explicit state information which may have been changed by invocations of useDelimiter(java.

Is it necessary to close Scanner Java?

It is recommended to always close the Scanner when we are reading a file. It ensures that no input or output stream is opened, which is not in use.


1 Answers

Try this:

in.nextLine(); 

This advances the Scanner to the next line.

like image 112
Makoto Avatar answered Oct 09 '22 07:10

Makoto