3.Java jump out of loop-break and Continue statements

Source: Internet
Author: User

In practical programming, it is sometimes necessary to jump out of a loop when a conditional statement is matched. In Java, it is controlled by the break and continue statements.

"Break" statement

The "break" statement is used to end the loop, that is, all loops behind it are no longer executed.

Example: Calculate the result of a 1+2+3+4......+100.
public class example1{
public static void Main (string[] args) {
int result=0;
for (int i=1;i<=100;i++) {
if (i>50) break;
Result+=i;
}
SYSTEM.OUT.PRINTLN (result);
}
}
Output Result:
1275

Analysis: The program only calculates the results of the 1+2+3+4+......+50, the back of the loop is not executed, that is, when the i=51, the cycle is over.

In addition, the "break" statement can be used with the switch switch statement, which is explained in the following section.

"Continue" statement

The "Continue" statement is used to end the current loop and into the next loop, that is, just this one cycle is over, not all loops are over, and the loop behind it continues.

Example: Calculate the result of a 1+2+3+4......+100.
public class example1{
public static void Main (string[] args) {
int result=0;
for (int i=1;i<=100;i++) {
if (i>50&&i<=60) continue;
Result+=i;
}
SYSTEM.OUT.PRINTLN (result);
}
}
Output Result:
4495

Analysis: The program calculates the results of the 1+2+3+......+48+49+50+61+62+63+......+100 and simply does not cycle the i=51,52......60.

3.Java jump out of loop-break and Continue statements

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.