Although the response of @ x-rw is valid, I think your program can be optimized, while controlling user input.
The following program:
- would limit to
3
the number of options that the user can write in the main menu
- in the option
1
you would control that the number of wagons is a numerical value using nextInt
and step you avoid having to convert that value.
- a structure
switch ... case
is used to give more clarity to the code. You could even pass the flow to a method, if the operations within the option involve a lot of code.
Code:
Scanner kboar = new Scanner(System.in);
boolean salir = false;
int opcion;
while (!salir || !kboar.hasNextInt()) {
System.out.println("1. Crear un vagon de personas.");
System.out.println("2. Crear un vagon de carga.");
System.out.println("3. Finalizar.");
try {
System.out.println("Escribe una de las opciones");
opcion = kboar.nextInt();
switch (opcion) {
case 1:
System.out.println("Ingrese cantidad de asientos:");
while (!kboar.hasNextInt()) {
System.out.println("¡Error!: Debe escribir un número. Ingrese cantidad de asientos:");
kboar.next();
}
int totalAsientos = kboar.nextInt();
System.out.println("OK, total de asientos:" + totalAsientos);
kboar.nextLine();
System.out.println("Ingrese color:");
String color = kboar.nextLine();
System.out.println("OK, el color es: " + color);
System.out.println("Vagon agregado con: "+totalAsientos+" asientos y de color: "+color);
System.out.println("_______________________________________");
/*
DePasajero vdp = new DePasajero();
vdp.asientos = totalAsientos;//Integer.valueOf(kboar.nextLine());
vdp.color = color;//kboar.nextLine();
t1.agregarVagon(vdp);
submenu(t1);
*/
break;
case 2:
//crearVagonCarga();
break;
case 3:
System.out.println("Cerrando programa...");
salir = true;
break;
default:
System.out.println("Solo números entre 1 y 3");
}
} catch (InputMismatchException e) {
System.out.println("¡Error!... Debes insertar un número");
kboar.next();
}
}
Normal operation test:
1. Crear un vagon de personas.
2. Crear un vagon de carga.
3. Finalizar.
Escribe una de las opciones
1
Ingrese cantidad de asientos:
5
OK, total de asientos:5
Ingrese color:
Rojo
OK, el color es: Rojo
Vagon agregado con: 5 asientos y de color: Rojo
Test operation controlling erroneous data:
Let's see:
1. Crear un vagon de personas.
2. Crear un vagon de carga.
3. Finalizar.
Escribe una de las opciones
f
¡Error!... Debes insertar un número
1. Crear un vagon de personas.
2. Crear un vagon de carga.
3. Finalizar.
Escribe una de las opciones
1
Ingrese cantidad de asientos:
h
¡Error!: Debe escribir un número. Ingrese cantidad de asientos:
87
OK, total de asientos:87
Ingrese color:
Verde
OK, el color es: Verde
Vagon agregado con: 87 asientos y de color: Verde