I have a program for handling flight reservations. My program consists of 3 classes: The main class, a class called Passenger that is for creating passenger's info, and a class that handles the registration of the flight info itself.
To handle seat registration, I first call a method Passenger.setSeatNumber() in main. This method then calls a method in Registration class and assigns the result of this operation to the seat number variable of the passenger, then in main, I assign that seat number via a getSeatNumber() method. (I know this is very verbose but the teacher expects us to understand OOP and multiple classes, so we're supposed to handle this stuff by using all these methods and classes)
Now, in my Registration method to assign a seat, I have an if statement that should evaluate to true if the user either tries to input a value less than 0 or greater than 20, or if the value entered is already present in a HashSet that contains the registered seats. If it evaluates to true, it should throw a custom exception to get the correct input. Problem is, the condition is never evaluating to true, even if I input a negative or if I go over 20, and the HashSet doesn't seem to be registering the numbers either.
public static int asientosReservados(int x) {
HashSet<Integer> asientos = new HashSet(21);
asientos.add(x);
//Añadir un duplicado a un HashSet no lanza un error, sino que la operación retorna false.
//Con este método, al retornar 0 para false
//o 1 para true, se puede más adelante determinar si ocurrió un duplicado.
if (asientos.add(x) == false) {
return 0;
} else {
return 1;
}
}
//Seleccionar y retornar asiento.
//Se va a revisar que sea en el rango correcto y que este no sea duplicado.
public void seleccionarAsiento() {
do{
try{
ExcepcionRegistro e = new ExcepcionRegistro("Ha ocurrido un error con el registro del asiento.");
System.out.println("\n\n Digite el número de asiento del 0 hasta el 20");
this.asiento = input.nextInt();
asientosReservados(this.asiento);
if(this.asiento < 0 || this.asiento > 20 || asientosReservados(this.asiento) == 0) {
throw e;
}
continuarCiclo = false;
}
//Bloque catch para determinar si el asiento estaba fuera de rango o si ya existia.
catch (ExcepcionRegistro e) {
if (this.asiento < 0 || this.asiento > 20){
System.out.println(e.getMessage());
System.out.println("\nPor favor seleccione nuevamente un asiento entre el 1 y el 20.");
input.nextLine();
} else {
System.out.println(e.getMessage());
System.out.println("\nEl asiento seleccionado ya está ocupado. Seleccione otro");
input.nextLine();
}
}
} while (continuarCiclo == true);
}
Aucun commentaire:
Enregistrer un commentaire