You can make your program more efficient and validate many things.
Pimero , the try-catch
is not a good idea for this exercise. Its use is reserved for other scenarios.
Second , in your case the best option is do-while
since you want to show the menu and ask for an option at least ONCE. That is, you need to run the code at least ONCE, no matter what. Here comes the do-while
. With this cycle you ensure that your code is compulsorily executed at least once and the evaluation is made after the first execution of the cycle.
Third , you must validate that the user only enters numbers. What would happen if the user enters letters or something else ?. Here you can use do-while
also, but since we want to validate whenever the data entered is a number then, in this case it is better to use while
.
Example (I have commented everything):
import java.util.Scanner;
public class SO {
public static void main(String[] args) {
int opcion = 0;
boolean salir = true;
Scanner scanner = new Scanner(System.in);
// Ciclo do-while
do {
System.out.println("1. Tablero 4 x 4");
System.out.println("2. Tablero 6 x 6");
System.out.println("3. Salir");
// Validar que el dato ingresado sea un número
do {
System.out.print("Escribe una de las opciones: ");
// Mientras sea diferente a un número
// Ciclo while
while (!scanner.hasNextInt()) {
System.out.println("\nError, tu respuesta no es un número!\n");
scanner.next();
System.out.print("Escribe una de las opciones: ");
}
// Finalmente, guardar el número y salir del ciclo
opcion = scanner.nextInt();
} while (opcion <= 0);
switch (opcion) {
case 1:
System.out.println("Has seleccionado la opcion de tablero 4x4.\n");
break;
case 2:
System.out.println("Has seleccionado la opcion de tablero 6x6.\n");
break;
case 3:
System.out.println("Programa finalizado...");
salir = false;
break;
default:
System.out.println("\nError, opción inválida!\n");
break;
}
} while (salir);
// Cerrar Scanner
scanner.close();
}
}
I hope I have helped you, regards!