【问题标题】:Java not asking for reinput after an InputMismatchExceptionJava 在 InputMismatchException 后不要求重新输入
【发布时间】:2020-02-21 21:26:17
【问题描述】:

我有一个为航空公司注册人员的示例程序。

在 Registration 类的 selectSeats 方法中,我有一个 try catch 块,如果用户输入非数值,catch 语句应该捕获 InputMismatchException。

但是,重新输入操作并没有发生,因此,当发生异常时,程序只是抛出错误消息并继续到最后(这会导致意外结果)

这是有问题的方法

    public void seleccionarAsiento() {
            boolean malaSeleccion = true;
            do{
                try{

                    System.out.println("\n\n Digite el número de asiento del 0 hasta el 20");
                    while (malaSeleccion) {

                        //Selección del hashSet correspondiente a cada vuelo mediante uso de la variable polimorfica "asientos".
                        if(this.destino.equals("Nicaragua")) {
                            asientos = asientosNCA;
                        }
                        else if (this.destino.equals("Panama") || this.destino.equals("Panamá")) {
                            asientos = asientosPNA;
                        }

                        this.asiento = input.nextInt(); //The part causing the issue

                        if(this.asiento < 0 || this.asiento > 20) {
                            System.out.println("\nSelect a seat between 0 and 20.");

                        } else if (asientos.contains(this.asiento)) {
                            System.out.println("\nSeat taken, select another one.");
                        } else if (this.asiento >= 0 && this.asiento <= 20 && asientos.contains(this.asiento) == false) {
                            asientos.add(this.asiento);
                            continuarCiclo = false;
                            malaSeleccion = false;
                        }
                    }            

                } // Fin de bloque try

                //Bloque catch para prevenir un input no numerico.
                catch (InputMismatchException inputMismatchException) {
                    System.out.println("Not numeric value, try again.");
                    input.nextLine();

                }

In case this is relevant, since I'm not sure if this could be related to a problem with Inheritance (but I doubt it because the exception is being caught)

This is the start of the class where that method is, and an extension to Exception I added.

    public class RegistroCompra {

        Scanner input = new Scanner(System.in);
        private String destino;
        private int asiento;
        private boolean continuarCiclo = true;


        public static HashSet<Integer> asientosNCA = new HashSet(21);
        public static HashSet<Integer> asientosPNA = new HashSet(21);

        HashSet<Integer> asientos = null;

        class ExcepcionRegistro extends Exception {
            ExcepcionRegistro(String s) {
                super(s);
            }
        }

} while (continuarCiclo == true); // Fin de bloque Do

编辑:我通过在 catch 块中使方法递归解决了这个问题。 因此,如果它捕获到 inputmismatchexception(因为它正在捕获它),它会使用 input.nextLine() 从无效输入中清除缓冲区,然后该函数再次调用自身以重新启动选择过程。

【问题讨论】:

  • 请标记出异常所在的行。请用英文编写代码。否则,您期望人们仅从技术角度理解您的代码。
  • 您似乎遗漏了一些代码。有一个包含 try .. catch 的 do 命令,但我们看不到它的结尾。这是您希望在出现异常时重复的循环吗?如果是这样,那么原因是您没有正确捕获异常。如果我们可以看到的 while 循环是您希望重复的,那么问题是异常被抛出了 while 循环。当捕获到异常时,会在 catch 部分关闭后继续执行,因此在您的情况下,您已经在 while 之外了。
  • 另外两点。我没有看到任何抛出该异常的东西,所以当然,它永远不会被捕获。其次,我无法想象您想在 catch 块中调用 input.nextline() 的情况。我假设有一个外部循环正在处理这些行。 catch 块应该在其中结束,因此它会落入终止行处理的相同代码中。
  • @akuzminykh 这些西班牙语消息的内容与手头的问题根本不相关,这就是我不翻译它们的原因。问题很清楚:它是一个数字输入,我指出它接受非数字输入并继续前进。
  • @Zag 抱歉,我错过了 do-while 的结尾,但它就在 catch 部分之后。它只是做 while(continuarCiclo == true) 并且无效输入异常不需要显式的 throw 声明,它们在发生时会自动抛出。至于 input.nextLine() 是清空输入的缓冲区,否则无效值会卡在那里。

标签: java exception error-handling inputmismatchexception


【解决方案1】:

按如下方式进行:

public void selectSeat() {
    boolean valid = true;
    do {
        System.out.println("Enter the seat number from 0 to 20");
        // ...
        try {
            this.asient = Integer.parseInt(input.nextLine());
            // ...
        } catch (InputMismatchException inputMismatchException) {
            System.out.println("This is not a numerical value, try again.");
            valid = false;
        }
    } while (!valid);
}

【讨论】:

    【解决方案2】:

    异常可能不是 InputMismatchException 的实例。您可以尝试添加异常 e 来查看真正的异常。

    
    catch (InputMismatchException inputMismatchException) {
      System.out.println("Este no es un valor númerico, intente de nuevo.");
      input.nextLine();
    }
    catch (Exception e) {
      exception.printStackTrace()
      input.nextLine();
    }
    
    

    【讨论】:

    • 不,它抓住了它,正确的类型和所有,它只是没有让我再次输入值,所以默认值 0 值
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-14
    相关资源
    最近更新 更多