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.
"quit"
before continuing to the third prompt. \$\endgroup\$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 singlescanner.nextLine()
. \$\endgroup\$