Why is good practice to empty the ‘Garbage’ from the input buffer in a block of code like this? What would happen if I didn’t?
try{
age = scanner.nextInt();
// If the exception is thrown, the following line will be skipped over.
// The flow of execution goes directly to the catch statement (Hence, Exception is caught)
finish = true;
} catch(InputMismatchException e) {
System.out.println("Invalid input. age must be a number.");
// The following line empties the "garbage" left in the input buffer
scanner.next();
}
Assuming you are reading from the scanner in a loop, if you don’t skip the invalid token, you will keep reading it forever. That’s what
scanner.next()does: it moves the scanner to the next token. See the below simple example, which outputs:Without the
String s = scanner.next()line, it would keep printing “Invalid input” (you can try by commenting out the last 2 lines).