我想捕獲 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
提交
取消