how do I get out of the if and return to the beginning of the loop?

0

enters the while loop, if I enter the correct value which in this case is 3, leaves the loop, but if not, I enter the if, and I do not leave there even if I enter the 3 again, how do I get out of the if and return to the beginning of the while?

String velas = "3";
String total ="";

while (total.equals(velas)== false){//aqui empieza el bucle     
    System.out.println("introduce tu respuesta");

    total = S.nextLine();


    if(total.equals(velas)==false){//este if es por si el usuario se equivoca

        System.out.println("respuesta incorreta, ¿quieres una pista? \n pista 1  \n pista 2 \n pista 3 ");



                int opcion = S.nextInt();

                switch(opcion){

                case 1:

                    System.out.println("Tienen que quedar cierta cantidad de velas al final");
                    break;
                case 2:

                    System.out.println("segunda pista");
                    break;

                case 3:

                    System.out.println("tercera pista");
                    break;

                    default:
                        System.out.print("no existe esa opción");


                }

    }


}
    
asked by Luis Sanches Larios 22.07.2017 в 06:17
source

2 answers

2

You have everything right except for one detail, when using a new line \n and use S.nextInt() only read and consume the next number entered, but not the new lines. To solve it I have two proposals, one is to replace

total = S.nextLine();

for

total = S.next();

The other would be to consume the space after reading the number, leaving as follows:

int opcion = S.nextInt();
S.nextLine();  // <-- Agregar esta linea

switch(opcion){
.........
    
answered by 22.07.2017 в 06:52
2

Since S.nextLine () is string:

int opción=0;
Try{ 
opcion = Integer.parseInt(S.nextLine());
}catch(Exception e){}

Instead of:

int opcion = S.nextInt();

I relied on the previous answer.

    
answered by 22.07.2017 в 07:57