【发布时间】:2017-09-30 02:27:19
【问题描述】:
对于我的一项任务,我们应该尝试捕获 InputMismatchException 并告诉用户输入给定的选项(在这种情况下,它可以是 1、2、3、4,没有别的)。出于某种原因,每当我尝试创建 try catch 块时,它都会让用户输入两次,但它仍然会使程序崩溃。这是我所拥有的:
do {
Scanner menuOptions = new Scanner(System.in);
System.out.println("1. Get another card");
System.out.println("2. Hold hand");
System.out.println("3. Print statistics");
System.out.println("4. Exit"+ "\n");
System.out.println("Choose an Option: ");
int selectedOption = menuOptions.nextInt();
try{
selectedOption = menuOptions.nextInt();
}
catch(InputMismatchException e){
System.out.println("Invalid input! Please select between options 1,2,3,4")
}
if (selectedOption == 1) {
//proceeds to do what is instructed if user input is 1}
else if (selectedOption ==2{
//proceeds to do what is instructed if user input is 2}
else if (selectedOption == 3) {
//proceeds to do what is instructed if user input is 3}
else if (selectedOption ==4{
//proceeds to do what is instructed if user input is 4}
知道如何使这项工作发挥作用吗?
【问题讨论】:
-
Check Out this answer希望这有帮助!
标签: java loops try-catch do-while