无法弄清楚如何捕获 InputMismatchException

Cannot Figure out how to catch 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 而不是其他任何内容。 扫描仪 class 已经实施,'scan' 将充当我的角色。

感谢您的帮助!

试试这个:

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。您不需要在异常处理程序中复制该行为。但是,您 需要做的是从扫描器中丢弃不匹配的令牌,以便扫描新令牌。

作为次要问题,您的 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();
    }
}