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();
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);
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.
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.
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.
Try this:
in.nextLine();
This advances the Scanner to the next line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With