The Java language does not provide a goto statement to control the jump, which improves the readability of program flow control, but reduces the flexibility of programmatic controls. To compensate for this deficiency, Java provides continue and break to control the loop structure, and in addition, return can end the entire method and end a loop.
One. Use break end loop
1. Forcibly terminate a loop when a condition arises, used to completely end a loop, and jump out of the loop body.
eg
for (int i=0;i<10;i++) {
if (i==2) {
No more execution of i=3 .... Jump straight out of the loop
Break
}
}
2.break not only can end the loop, you can also directly end its outer loop, you need to immediately follow a tag after the break, which is used to represent an outer loop, the label is followed by the following: identifier. Labels are useful only if they are placed before a loop statement
eg
Outer
for (int j=0;i<5;j++) {
for (int i=0;i<3;i++) {
if (i==1) {
Jump out of the loop identified by the outer label
Break outer;
}
}
}
Two. Use continue to ignore the remaining statements in this cycle
1.eg:
for (int i=0;i<10;i++) {
if (i==2) {
I equals 2 o'clock, will not execute the statement below, enter i=3 continue to execute
Continue
}
System.out.println ("hello!");
2. Similar to a break, continue can also be used with a label to skip the remaining statements of the second loop of the loop that is identified by the label
Three. Use return End method
The 1.return is not a keyword used specifically for loop structure control, but is used to end a method that ends when a method executes to a return statement, and the loop naturally ends. Unlike Break,continue, return closes the entire method directly, regardless of the number of loops within it.