在java中,如果想要跳出for循环,一般情况是使用:break,continue。
break:是跳出当前循环,continue:是跳出本次循环。
如下面的例子:
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+" ");
}
}
}
输出:0 1 2 3 4
也就是说,break会跳出(终止)当前循环。
continue是跳出当前循环,开使下一循环,如下所示:
[java]
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) {
continue;
}
System.out.print(i+" ");
}
}
}
输出:0 1 2 3 4 6 7 8 9
以上都没有办法跳出多重循环,在java中跳出多重循环则需要使用标签,然后在需要跳出的地方,用break lable就行了。
public class RecTest {
/**
* @param args
*/
public static void main(String[] args) {
loop: for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
for (int k = 0; k < 10; k++) {
for (int h = 0; h < 10; h++) {
if (h == 6) {
break loop;
}
System.out.print(h);
}
}
}
}
System.out.println("\nI'm here!");
}
}
输出:
012345
I'm here!
意思很显然!
当然还有另外一种方法,这也是设置一个boolean值的标记位,在for循环中使用判断是否继续循环来达到目的。
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++) { //当flag为true时跳出循环
if(flag == true) {
break;
}
for (int j = 0; j < array[i].length; j++) {
if (array[i][j] == 8) {
flag = true;
break;
}
}
}
System.out.println(flag);
}
}
通过设置标志位,实现里成的代码控制外层的的循环条件。