Catch/try 不适用于扫描仪的输入不匹配异常?

Catch/try not working for input mismatch exception with scanner?

好吧,我正在学习 CS 安全 class,里面有一些基本的 java 编程,我们的第一个任务是玩 BigInteger。但是,我们还得"bullet proof"我们的程序。虽然我的方法不是最理想的,但它适用于第一个输入。也就是说,如果我为任何 input.new---(); 输入无效输入,我的程序将提示用户使用有效数字重试。但是第一个 input.nextInt(); 仍然会接受无效输入并崩溃,显示 "java.util.InputMismatchException" 然后继续扫描仪。关于为什么会发生这种情况的任何想法? p.s。程序在任何情况下都不得显示错误日志。

import java.io.*;
import java.util.*;
import java.math.*;

class BigNumber{
   public static void main(String args[]){

     while(true){ 
      try{
         Scanner input = new Scanner(System.in);

         System.out.print("if you wish to exit the program type in '0,' to continue running the program type in any other value: ");
         double esc= input.nextDouble();
         if(esc == 0){ break;}
         else{System.out.println("Ok, program running...");}
         input.nextLine();

         System.out.print("Enter number a: ");
         String aValue = input.nextLine();

         System.out.print("Enter number b: ");
         String bValue = input.nextLine();

         System.out.print("Enter a number 'n': ");
         String nValue = input.nextLine();
         while (Integer.parseInt(nValue) < 1)
         {
            if (Integer.parseInt(nValue) < 1)
            {
               System.out.print("Please enter a valid number (n>1): ");
               nValue = input.nextLine();
            }
         }

         BigInteger a= new BigInteger(aValue);
         BigInteger b= new BigInteger(bValue);
         BigInteger n= new BigInteger(nValue);

         System.out.println("---------------------------");
         System.out.println("1) a xor b: " + a.xor(b));
         System.out.println("2) b xor b: " + b.xor(b));
         System.out.println("3) a xor b xor a: " + a.xor(b).xor(a));
         System.out.println(" ");
         System.out.println("4) ab mod n: " + a.modPow(b,n));
         System.out.println(" ");
         System.out.println("5) a shifted to the right by 6: " + a.shiftRight(6));
         System.out.println("6) b shifted to the left by 3: " + b.shiftLeft(3));
         System.out.println("---------------------------");

      }
      catch (NumberFormatException e){
         System.out.println("-----> Please try entering a valid number(s) <-----");
      }

    } 
  }
}

您的 catch 块仅处理 NumberFormatException。如果您要处理所有 Exception(s),那么我建议您更改此

catch (NumberFormatException e){

类似于

catch (Exception e){

nextDouble() 将读取双精度值。如果 parseDouble 失败,则抛出 InputMismatchException

这里是class的代码:

public double nextDouble() {
    // Check cached result
    if ((typeCache != null) && (typeCache instanceof Double)) {
        double val = ((Double)typeCache).doubleValue();
        useTypeCache();
        return val;
    }
    setRadix(10);
    clearCaches();
    // Search for next float
    try {
        return Double.parseDouble(processFloatToken(next(floatPattern())));
    } catch (NumberFormatException nfe) {
        position = matcher.start(); // don't skip bad token
        throw new InputMismatchException(nfe.getMessage());
    }
}

甲骨文说

public class InputMismatchException extends NoSuchElementException Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.

public class NumberFormatException extends IllegalArgumentException Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.

您只在 catch 块中使用了 NumberFormatException,因此它只捕获了 NumberFormatException。要捕获其他异常,您必须添加其他 catch 块

catch (NumberFormatException e){
         System.out.println("-----> Please try entering a valid number(s) <-----");
catch (InputMismatchException e){
         System.out.println("-----> Please try entering a valid number(s) <-----");

或 如果您使用基本异常 class 它将捕获任何类型的异常

catch (Exception e){
         System.out.println("-----> Please try entering a valid number(s) <-----");

InputMismatchExceptionNumberFormatException不同类。它们之间没有关系,您的程序抛出 InputMismatchException 而您正试图捕获 NumberFormatException。对于 InputMismatchException 异常,您还需要一个 catch 块。