In Java, if you want to jump out of a for loop, the general situation is to use: Break,continue.
Break: is to jump out of the current cycle, continue: is out of this cycle.
As in the following example:
Package Com.xtfggef.algo;
public class Rectest {
/**
* @param args
*/
public static void Main (string[] args) {
for (int i=0; i<10; i++) {
if (i==5) {
Break
}
System.out.print (i+ "");
}
}
}
Output: 0 1 2 3 4
In other words, the break jumps out (terminates) the current loop.
Continue is to jump out of the current loop, open the next loop, as follows:
[Java]
Package Com.xtfggef.algo;
public class Rectest {
/**
* @param args
*/
public static void Main (string[] args) {
for (int i = 0; i < i++) {
if (i = = 5) {
Continue
}
System.out.print (i+ "");
}
}
}
Output: 0 1 2 3 4 6 7 8 9
There is no way to jump out of multiple loops, in Java to jump out of multiple loops, you need to use the label, and then in need of jump out of place, with break lable on the line.
public class Rectest {
/**
* @param args
*/
public static void Main (string[] args) {
loop:for (int i = 0; i < i++) {
for (int j = 0; J < J + +) {
for (int k = 0; k < k++) {
for (int h = 0; h < h++) {
if (h = = 6) {
Break loop;
}
System.out.print (h);
}
}
}
}
System.out.println ("\ni ' m here!");
}
}
Output:
012345
I ' m here!
The meaning is obvious.
Of course there is another way, which is to set a Boolean value of the tag bit, in the for loop to use to determine whether to continue looping to achieve the goal.
public class Breaklfor {
public static void Main (String args[]) {
int array[][] = {5, 7, 6, 4, 9}, {1, 2, 8, 3, 2}};
Boolean flag = false;
for (int i = 0; i < Array.Length i++) {//Jump out of loop when flag is true
if (flag = = True) {
Break
}
for (int j = 0; J < Array[i].length; J +) {
if (array[i][j] = = 8) {
&N Bsp flag = true; &NBSP
break
&N Bsp }
}
&NBSP ; &NBSP
SYSTEM.OUT.PRINTLN (flag);
}
}
by setting The sign bit that implements the loop condition in which the code controls the outer layer.