Submenu in Java and conditional switch [closed]

0

I have a problem with my code, the problem arises when I leave a Submenu to return to the main menu, what happens is that when I leave the Submenu I am executing the switch default and I do not understand why who does it.

Main Menu Code:

int opcion;
    do {

        opcion = Integer.parseInt(JOptionPane.showInputDialog("Seleccione una opcion. "
                + "\n 1. Crear producto. "
                + "\n 2. Modificar producto. "
                + "\n 3. Salir."));

        switch (opcion) {

            case 1: crearProducto();
                    break;

            case 2: modificarProducto();
                    break;

            case 3: JOptionPane.showMessageDialog(null, "Hasta pronto.", "Hasta pronto", JOptionPane.INFORMATION_MESSAGE);
                    break;

            default: JOptionPane.showMessageDialog(null, "Dato no valido.", "Error", JOptionPane.ERROR_MESSAGE);
        }

    } while (opcion != 3);

Submenu code:

int opcion;
    do {

        opcion = Integer.parseInt(JOptionPane.showInputDialog("Que producto desea modificar. "
                + "\n 1. Productos solidos. "
                + "\n 2. Productos liquidos. "
                + "\n 3. Volver al Menu Principal."));

        switch (opcion) {

            case 1: modificarSolidos();
                    break;

            case 2: modificarLiquido();
                    break;

            default: JOptionPane.showMessageDialog(null, "Dato no valido.", "Error", JOptionPane.ERROR_MESSAGE);
                     break;
        }

    } while (opcion != 3);

PS: BOTH ARE CREATED IN SEPARATE METHODS.

Thank you.

    
asked by CamiloJc 12.03.2017 в 20:00
source

1 answer

1

If you look at your submenu you have not taken into account when the user enters the number 3 that in your submenu would go to the main menu.

That's why you're running the default option before exiting the loop since the loops do-while first run and then perform the comparison, that is, when you enter the number 3 the option will be executed default and then exit the loop.

    
answered by 12.03.2017 / 20:05
source