-1
爲什麼最好的做法是在這樣的代碼塊中清空輸入緩衝區中的「垃圾」?如果我沒有,會發生什麼?Java輸入緩衝區垃圾
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();
}