添加
keyboard.nextLine()
continue
,当发生异常时,您需要“吃掉”输入:
catch (InputMismatchException e){
System.out.println("-----------------------------------------------------------");
System.out.println("This is not a number. Please choose from the following: \n");
choices();
keyboard.nextLine();
continue;
// numberEntered = keyboard.nextInt();
}
编辑
,我更改了您的一些代码:
public void whatToDo(){
System.out.println("");
System.out.println("");
System.out.println("=====================================");
System.out.println("Welcome");
System.out.println("=====================================\n");
System.out.println("What would you like to do today? Your choices are: \n");
Scanner keyboard = new Scanner(System.in);
do{
try{
choices();
System.out.println("");
System.out.println("Please enter your choice");
int numberEntered = keyboard.nextInt();
if (numberEntered >= 1 && numberEntered <= 3) {
System.out.println("That is a good CHOICE");
madeChoice = true;
} else {
System.out.println("-----------------------------------------------------------");
System.out.println("That is not a choice. Please choose from the following: \n");
}
}catch (InputMismatchException e){
System.out.println("-----------------------------------------------------------");
System.out.println("This is not a number. Please choose from the following: \n");
keyboard.next();
// numberEntered = keyboard.nextInt();
}
}while(!madeChoice);
}