我有一个示例程序,可以为航空公司注册人员。
在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()从无效输入中清除缓冲区,然后,该函数再次调用自身以重新开始选择过程。
最佳答案
如下进行:
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);
}