У меня есть пример программы, которая регистрирует людей для авиакомпании.
В классе Registration, на методе selectSeats, у меня есть блок try catch, где оператор catch должен перехватывать InputMismatchException в случае ввода пользователем не числовое значение c.
Однако операция повторного ввода не происходит, поэтому вместо этого, когда возникает исключение, программа просто выдает сообщение об ошибке и переходит к концу (что приводит к неожиданным результатам )
Это рассматриваемый метод
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 (), а затем снова вызывает функцию, чтобы перезапустить процесс выбора.