我想捕获 InputMissmatchException 但不停止重新执行代码(我希望 while 循环再次重新运行,直到给出适当的输入)整数选择 = 0;布尔循环=真; while(loop){ printInstruction(); choice = scanner.nextInt(); //catch InputMissmatchException switch(choice){ case 0: loop = false; break; case 1: addCustomer(mohamad,sgbl); break; case 2: deleteCustomer(sgbl); break; case 3: seeInfo(sgbl); break; case 4: makeTransaction(mohamad); break; case 5: seeTransactionLog(mohamad); break; default: System.out.println("try again"); } }
1 回答
郎朗坤
TA贡献1921条经验 获得超9个赞
int a = -1;
while(true)
{
try
{
Scanner in = new Scanner(System.in);
a = in.nextInt();
}
catch(InputMismatchException e)
{
e.printStackTrace();
}
//Your switch statement
}
顺便说一下,a 的默认值设置为 -1。如果发生异常,则进入 switch case 时的值将是 -1。
int a = -1;
while(true)
{
try
{
Scanner in = new Scanner(System.in);
a = in.nextInt();
}
catch(InputMismatchException e)
{
e.printStackTrace();
continue;
}
//Your switch statement
}
如果您使用 continue 则循环的当前迭代将停止并运行下一次迭代
添加回答
举报
0/150
提交
取消