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):
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;
}
}
In Python, the break statement provides you with the opportunity to exit out of a loop when an external condition is triggered. You'll put the break statement within the block of code under your loop statement, usually after a conditional if statement.
The Java break statement is used to break loop or switch statement. It breaks the current flow of the program at specified condition. In case of inner loop, it breaks only inner loop. We can use Java break statement in all types of loops such as for loop, while loop and do-while loop.
break command (C and C++) The break command allows you to terminate and exit a loop (that is, do , for , and while ) or switch command from any point other than the logical end. You can place a break command only in the body of a looping command or in the body of a switch command.
The only way to exit a loop, in the usual circumstances is for the loop condition to evaluate to false. There are however, two control flow statements that allow you to change the control flow. continue causes the control flow to jump to the loop condition (for while, do while loops) or to the update (for for loops).
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With