Java simple way to jump out of multilayer loops

Source: Internet
Author: User

Multiple loops can be used in Java programs to handle complex logic. But it's a hassle to jump out of the outermost loop from the inner loop. The following code is an example of a three-tier loop:

String[] arr= new string[]{"A", "B", 

"C"};
for (string S:arr)
{to
    (string Ss:arr) {for
        (string sss:arr)
        {
            System.out.println (SSS);
        }
    }
}

If you want to jump out of the first loop from the third tier, you can do this by setting a flag, but that's a bit cumbersome. Of course, developers who have used C or C + + can think of a goto statement, as shown in the following code:

String[] arr= new string[]{"A", "B", 

"C"};
for (string S:arr)
{to
    (string Ss:arr) {for
    (string
        sss:arr)
        {
            System.out.println ( SSS);
            goto label;
        }
    }
Label

Although the above code seems to be feasible, although Java also has the GOTO keyword, but this keyword is not used (the Java compiler throws an exception). However, Java also provides another kind of goto-like solution, which is break n and Continue N. where n represents the label name. Only in Java can you define a for, while, do...while three circular statements, and there can be no other statements between the label and the loop body, as the following label definition is legal:

label: //定义标签
for(int i=0;i<10;i++)
{
  ... ...
}

The following label definitions are not valid:

label: //定义标签
System.out.println("abcd"); //此处不能有任何Java语句
for(int i=0;i<10;i++)
{
  ... ...
}

The code to jump out of the multi-layer loop using break N is as follows:

Labela: For
(string S:arr)
{for (
    string Ss:arr) {for (string
        Sss:arr)
        {
            System.out.print (SSS);
            Break Labela;
        }
    }  

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.