Introduction to Java Syntax (vii): Brake and label

Source: Internet
Author: User

1:break

The break statement provides a convenient way to jump out of a loop.

boolean test=true;
   int i=0;
   while(test)
{
    i++;
    if(i>=10) break;
}

When you execute this program, the full loop runs only 10 times, although the while condition expression is always true.

2: Label label

Marking provides a simple method of controlling loops that cannot be implemented by a break statement, which terminates when a break is encountered in a loop statement, regardless of other control variables. But what happens when you nest in a few layers of loops and want to quit the loop? The normal break only exits a cycle, and you can use the label to mark out which statement you want to exit.

char a;
   outer: //this is the label for the outer loop
   for(int i=0;i<10;i++)
   {
   for(int j=0;j<10;j++)
     {
       a=(char)System.in.read();
       if(a==´b´)
         break outer;
       if(a==´c´)
         continue outer;
     }
   }

In this example, the loop accepts 100 input characters from the keyboard, and when you enter the "B" character, the break outer statement ends the double loop, paying attention to the continue outer statement, which tells the computer to exit the current loop and continue to perform the outer loop.

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.