How to break from a loop after the condition is met

63,856

Use the break statement to break out of a loop completely once your condition has been met. Pol0nium's suggestion to use continue would not be correct since that stops the current iteration of the loop only.

while(foo)
{
    if(baz)
    {
        // Do something
    }
    else
    {
        // exit condition met
        break;
    }
}

All this having been said, good form dictates that you want clean entry and exit points so that an observer (maybe yourself, revisiting the code at a later date) can easily follow its flow. Consider altering the boolean that controls the while loop itself.

while(foo)
{
    if(baz)
    {
        // Do something
    }
    else
    {
        // Do something else
        foo = false;
    }
}

If, for some reason, you can't touch the boolean that controls the while loop, you need only compound the condition with a flag specifically to control your while:

while(foo && bar)
{
    if(baz)
    {
        // Do something
    }
    else
    {
        // Do something else
        bar = false;
    }
}
Share:
63,856
user2252310
Author by

user2252310

Updated on July 09, 2022

Comments

  • user2252310
    user2252310 almost 2 years

    Hi I have been trying for the past hour to break from this loop and continue since already met my condition once. My application pretty much reads a serie of lines and analyzes it and then prints the variable stated. An example of how the lines look like (the . are not included):

    • 10 c = 9+3
    • 20 a = c+1
    • 30 print c
    • 40 goto 20
    • 50 end

    It does everything right, when it gets to line 40 goes to line 20 as expected, but i want it to go to line 50 since already went to line 40 once. Here is my code for this part:

    while(booleanValue)
    {
        if(aString.substring(0, 4).equals("goto"))
        {
            int chosenLine = Integer.parseInt(b.substring(5));
            if(inTheVector.contains(chosenLine))
            {
                analizeCommands(inTheVector.indexOf(chosenLine));
                i++;
            }
            else
            {
                System.ou.println("Line Was Not Found");
                i++;
            }
        }
    
        else if(aString.substring(0, 3).equals("end"))
            {
                System.out.println("Application Ended");
                booleanValue = false;
            }
    }
    
  • user2252310
    user2252310 about 11 years
    it keeps looping even if i use do while. the problem is that it does not go to line 50. it keeps looping in between line 20 and 40.