1

I have a sample program which registers people for an airline.

At the Registration class, on the selectSeats method, I have a try catch block, where the catch statement should catch InputMismatchException in case the user inputs a non numeric value.

However, the reinput operation isn't happening, so instead, when an exception happens, the program just throws the error message and proceeds to the end (which leads to unexpected results)

This is the method in question

    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

Edit: I solved the issue by making the method recursive in the catch block. So if it catches the inputmismatchexception (because it was catching it), it cleans the buffer from the invalid input with input.nextLine() and then, the function calls itself again to restart the selection process.

Dasphillipbrau
  • 524
  • 2
  • 8
  • 17
  • Please mark the line where the exception is thrown. And please write code in english. Otherwise you are expecting people to understand your code just from a technical perspective only. – akuzminykh Feb 21 '20 at 21:40
  • 1
    You seem to be missing some code. There is a do command that wraps the try .. catch, but we don't see the end of that. Is that the loop that you expect to repeat when there is an exception? If so, then the reason is that you aren't catching the exception correctly. If the while loop that we can see is what you are hoping to repeat, then the problem is that the exception is throwing out of the while loop. When an exception is caught, then execution continues on the line after the catch section closes, so in your case you're already outside the while. – Zag Feb 21 '20 at 21:49
  • Two other points. I don't see anything throwing that exception, so, of course, it's never going to be caught. Second, I can't imagine a situation in which you want to be calling input.nextline() inside your catch block. I assume that there is an outer loop that is processing the lines. The catch block should end just inside that, so it then falls into the same code which terminates the processing of a line. – Zag Feb 21 '20 at 21:54
  • @akuzminykh the contents of those messages in spanish is not really relevant at all for the problem at hand, thats why I don't translate them. The issue is pretty clear: Its a numerical input and Im pointing out that its accepting non numeric inputs and moving on. – Dasphillipbrau Feb 21 '20 at 22:00
  • @Zag sorry, I missed the end of the do-while but its right there after the catch part. Its just do while(continuarCiclo == true) And invalid input exceptions don't need an explicit throw declaration, they're automatically thrown when they happen. As for the input.nextLine() it's to clear the buffer of input, otherwise the invalid value would be stuck there. – Dasphillipbrau Feb 21 '20 at 22:02
  • I've tried to run this code, but I'm getting very confused about what's suppose to be where. Moving the last while up prior to the class makes the while loop look complete. However, your `RegistroCompra` class doesn't end, and your `seleccionarAsiento` method also doesn't end. The `RegistroCompra` isn't used in your code, so now I don't know how to help you. – Scratte Feb 21 '20 at 23:12

2 Answers2

0

The exception may not the instance of InputMismatchException. You could try add Exception e to take a look the real exception.


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();
}

YouXiang-Wang
  • 1,119
  • 6
  • 15
0

Do it as follows:

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);
}
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110