This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5个答案)
2年前关闭。
在我的程序中,我试图让用户在1-3之间输入一个整数,然后根据他们键入的内容进行操作。如果不是数字或不是选项之一,则它将允许他们重新输入有效的选项。
我遇到的问题是,我无法集思广益如何使其不无限循环,而在控制台告诉他们输入了无效的输入之后,只允许他们输入数字。
(5个答案)
2年前关闭。
在我的程序中,我试图让用户在1-3之间输入一个整数,然后根据他们键入的内容进行操作。如果不是数字或不是选项之一,则它将允许他们重新输入有效的选项。
我遇到的问题是,我无法集思广益如何使其不无限循环,而在控制台告诉他们输入了无效的输入之后,只允许他们输入数字。
int i = 0;
while (i < 1) {
try {
int level = scan.nextInt();
i+=1;
if (level == 1) {
System.out.println("You selected level 1!");
//Start the game
} else if (level == 2) {
System.out.println("You selected level 2!");
//Start the game
} else if (level == 3) {
System.out.println("You selected level 3!");
//Start the game
} else {
System.out.println("That's not an option!");
i-=1;
}
} catch(InputMismatchException input) {
System.out.println("That's not an option!");
i-=1;
}
}
最佳答案
输入无效的输入时,需要清除它。触发输入异常时添加scan.next()
以便用next()清除它:
catch(InputMismatchException input) {
System.out.println("That's not an option!");
scan.next();
i-=1;
}