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