The break statement function in Java is generally the same as the C language,
Used in a loop statement to end the current loop.
But sometimes in a loop-nested statement, you just rely on a
A break statement is not enough to be implemented.
Cases:
If you want the sum to be output directly at 501, is this the code OK?
Check out the results!
。
Why is that?
Because the break terminates only the inner loop,
After J + +, the inside of the k++ loop body will still be executed again.
So, is there any way we can make sum output at 501?
The answer is, you need to use a very peculiar thing called the label.
How to use the label:
Label name:
=====================================================
Class Breakouter
{
public static void Main (string[] args)
{
int sum=0;
outer:for (int i=0;i<10;i++) {
for (int j=0;j<10;j++) {
for (int k=0;k<10;k++) {
sum++;
if (sum>500) {
Break outer;
}
}
}
}
SYSTEM.OUT.PRINTLN (sum);
}
}
Here, the label outer represents the outermost loop, the break outer, which represents the end of the entire large cycle.
Take a look at the execution results.
Sum greater than 500 immediate output, perfect solution.
about how the break statement ends the nesting of multiple loops