Exit nested while loops in java

1

I have the following structure:

do{
    do{
        if(){
        }
    }while(); 
}while();

All this within a method. If the condition of the if is fulfilled, I want to leave the 2 loops do while, but continue in the function. I tried return but it quits the function.

Thank you.

    
asked by Mario Hernandez 19.12.2017 в 19:59
source

2 answers

1

Try adding a flag to know if you have the while:

boolean stop = false;
do{

    do{
        if(){
           stop = true;
        }
    }while(!stop); 
}while(!stop);

In this case if stop happens to false , both while will stop.

    
answered by 19.12.2017 в 20:04
1

Based on this answer from the famous Jon Skeet, you can assign a name to the external cycle, and use break for Escape out of the external cycle:

void Metodo() {
    // mas código

    ciclo_externo:           // le asignas un nombre al ciclo aquí
    do{
        do{
            if(){
                // esto te saca de ambos ciclos de una vez.
                break ciclo_externo; 
            }
        }while(); 
    }while();

    // mas código
}

Or, probably the best option is to move the 2 cycles to a different method so you can use return without problem:

void Metodo() {
    // mas código

    ejecutarCiclos();

    // mas código
}

void ejecutarCiclos() {
    do{
        do{
            if(){
                return; 
            }
        }while(); 
    }while();
}
    
answered by 19.12.2017 в 20:10