for 循环都知道,条件判断中用 break ,就终止整个循环。这都知道。
某天碰到了 for 循环中用 continue ,平常基本不用,有点懵。记录下他们的差别。
for 循环中用 break ,终止整个 for 循环 。
for 循环中用 continue ,终止本次循环,执行下一次循环。
package com.lah.testcondition;
public class TestFor {
public static void main(String[] args) {
forWithContinue();
System.out.println("\n");
forWithBreak();
}
public static void forWithContinue(){
for (int k = 0; k < 10 ; k++){
if (k < 5){
continue;
}
System.out.println("forWithContinue, k = " + k);
}
}
public static void forWithBreak(){
for (int k = 0; k < 10 ; k++){
if (k == 3){
break;
}
System.out.println("forWithBreak, k = " + k);
}
}
}
运行结果,
forWithContinue, k = 5
forWithContinue, k = 6
forWithContinue, k = 7
forWithContinue, k = 8
forWithContinue, k = 9
forWithBreak, k = 0
forWithBreak, k = 1
forWithBreak, k = 2