1.标签
//i=0
//k=0
//k=1
private static void loop1() {
for1:
for (int i = 0; i < 3; i++) {
System.out.println("i=" + i);
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 3; k++) {
System.out.println("k=" + k);
if (k == 1) {
break for1;
}
}
}
}
}
//i=0
//k=0
//k=1
//i=1
//k=0
//k=1
//i=2
//k=0
//k=1
private static void loop2() {
for1:
for (int i = 0; i < 3; i++) {
System.out.println("i=" + i);
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 3; k++) {
System.out.println("k=" + k);
if (k == 1) {
continue for1;
}
}
}
}
}
2.外层的循环条件在内层代码控制
//i=0
//j=0
//j=1
private static void loop3() {
boolean flag = true;
for (int i = 0; i < 3 && flag; i++) {
System.out.println("i=" + i);
for (int j = 0; j < 3 && flag; j++) {
System.out.println("j=" + j);
if (j == 1) {
flag = false;
}
}
}
}
3.异常
//i=0
//j=0
//j=1
//--------------
private static void loop4() {
try {
for (int i = 0; i < 3; i++) {
System.out.println("i=" + i);
for (int j = 0; j < 3; j++) {
System.out.println("j=" + j);
if (j == 1) {
throw new Exception();
}
}
}
} catch (Exception e) {
System.out.println("--------------");
}
}
4.return
//i=0
//j=0
//j=1
private static void loop5() {
for (int i = 0; i < 3; i++) {
System.out.println("i=" + i);
for (int j = 0; j < 3; j++) {
System.out.println("j=" + j);
if (j == 1) {
return;
}
}
}
}