无法弄清楚如何捕获InputMismatchException

所以这是我当前捕获InputMismatchException错误的代码

int weapon = 0 boolean selection = true; while(selection) { try { System.out.println("Pick number 1, 2, or 3."); weapon = scan.nextInt(); selection = false; } catch(InputMismatchException e) { System.out.println("Choose 1,2,3"); weapon = scan.nextInt(); } } 

我正在尝试确保输入int而不是其他任何东西。 扫描仪类已经实现,“扫描”将对我起作用。

感谢您的帮助!

试试这个:

 int weapon = 0; do{ System.out.println("Pick number 1, 2, or 3."); if(scan.hasNextInt()){ weapon = scan.nextInt(); break; }else{ System.out.println("Enter an integer only"); scan.nextLine(); } }while(true); 

这将确保它是一个整数,它将一直询问,直到它得到它。

首先,您已经有一个循环用于提示并扫描所需的int 。 您不需要在exception处理程序中复制该行为。 但是,您需要做的是丢弃扫描仪中的不匹配令牌,以便扫描新的令牌。

作为次要问题,您的selection变量似乎是多余的。

看起来这可能会做你想要的事情:

 int weapon = 0 while(weapon < 1 || weapon > 3) { try { System.out.println("Pick number 1, 2, or 3."); weapon = scan.nextInt(); } catch(InputMismatchException e) { //discard the mismatching token scan.next(); } }