I have a while (true)
loop that has a try and catch
block inside In it. But when InputMismatchException
occurred, the while code runs twice without any user input. Without try and catch
while part is running correctly. I can't understand what is the problem here.
while (true) {
try {
System.out.println("Enter the option here: ");
option = scanner.next();
if (option.equalsIgnoreCase("V")){
viewCabins(cruiseShip);
} else if (option.equalsIgnoreCase("A")){
System.out.println("Enter the cabin number (0 - 11)");
cabinNum = scanner.nextInt();
System.out.println("Enter name of the passenger: ");
customerName = scanner.next();
addCustomer(cruiseShip, customerName, cabinNum);
System.out.println("Wrong Cabin number");
} else if (option.equalsIgnoreCase("Q")){
System.out.println("Thank you!");
break;
} else if (option.equalsIgnoreCase("E")){
emptyCabins(cruiseShip);
} else if (option.equalsIgnoreCase("D")){
System.out.println("Enter the room number (0 - 11)");
cabinNum = scanner.nextInt();
System.out.println("Enter name of the customer");
customerName = scanner.next();
System.out.println("Do you really want to delete this customer? ");
deleteOption = scanner.next();
if (deleteOption.equals("yes")){
deleteCustomer(cruiseShip, customerName, cabinNum);
}
} else if (option.equalsIgnoreCase("F")){
System.out.println("Enter name of the customer: ");
customerName = scanner.next();
findCabin(cruiseShip, customerName);
} else if (option.equalsIgnoreCase("S")){
loadToFile(cruiseShip);
System.out.println("Program data saved successfully");
} else if (option.equalsIgnoreCase("L")){
loadFromFile(cruiseShip);
System.out.println("Program data loaded successfully");
} else if (option.equalsIgnoreCase("O")){
System.out.println("Passengers alphabetically by name: ");
customerSort(cruiseShip);
}
}catch (InputMismatchException e){
System.out.println("Wrong Input! Please try again.");
}
}
Here is the output:
Enter the option here:
a
Enter the cabin number (0 - 11):
the
Wrong Input! Please try again.
Enter the option here:
Enter the option here:
CodePudding user response:
When the Scanner
throws an exception or simply doesn't read a token the typed input will remain inside of the Scanner
s buffer . So, when you entered "the"
when the Scanner
expects an int
via nextInt()
, the InputMismatchException
is thrown and handled in your catch
clause. "the"
however is not consumed when this happens and therefore still remains in the Scanner
s buffer.
On the next loop iteration, the call to Scanner#next()
consumes this token. However the read token doesn't fit any of your if
-criteria, so nothing happens and the loop repeats again.
To fix this, clear the Scanner
s buffer in your catch
clause via next()
/ nextLine()
.
CodePudding user response:
Try This:
while(true){
//your variables use Inside the while
String option,customerName,deleteOption;
Scanner scanner=new Scanner(System.in);
int cabinNum;
try{
//do samething
}
catch(Exception e){//do samething}
}