在Java中, 标签必须在循环之前使用, 一个循环之中嵌套另一个循环的开关, 从多重嵌套中continue或break.
控制循环:
1. continue会退回最内层的循环开头, 并继续执行;
2. 带标签的continue会到达标签的位置, 重新进入标签下面的循环;
3. break会中断并跳出当前循环;
4. 带标签的break会中断跳出标签下面的循环.
for循环的标签示例
//: Main.java
/**
* for循环标签
*/
class Main {
public static void main(String[] args) {
int i=0;
outer:
for (;true;) {
inner:
for (; i<10; i++) {
System.out.println("i = " + i);
if (i==2) {
System.out.println("continue");
continue;
}
if (i==3) {
System.out.println("break");
++i;
break;
}
if (i==7) {
System.out.println("continue outer");
i++;
continue outer;
}
if (i==8) {
System.out.println("break outer");
break outer;
}
for (int k=0; k<5; k++) {
if (k==3) {
System.out.println("continue inner");
continue inner;
}
}
}
}
}
}
/**
* Output:
i = 0
continue inner
i = 1
continue inner
i = 2
continue
i = 3
break
i = 4
continue inner
i = 5
continue inner
i = 6
continue inner
i = 7
continue outer
i = 8
break outer
*///:~
while循环的标签示例
//: Main.java
/**
* while循环标签
*/
class Main {
public static void main(String[] args) {
int i=0;
outer:
while (true) {
System.out.println("Outer while loop");
while (true) {
i++;
System.out.println("i = " + i);
if (i == 1) {
System.out.println("continue");
continue;
}
if (i == 3) {
System.out.println("continue outer");
continue outer;
}
if (i == 5) {
System.out.println("break");
break;
}
if (i == 7) {
System.out.println("break outer");
break outer;
}
}
}
}
}
/**
* Output:
Outer while loop
i = 1
continue
i = 2
i = 3
continue outer
Outer while loop
i = 4
i = 5
break
Outer while loop
i = 6
i = 7
break outer
*///:~
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-16 03:22:14