about how the break statement ends the nesting of multiple loops

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.