一、break语句——终止循环
break \\不带标签
break label \\带标签跳转,label是标签名
public class HelloWorld {
public static void main(String[] args) {
int numbers[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (int i = 0; i < numbers.length; i++) {
if (i == 3) {
// 跳出循环
break;
}
System.out.println("Count is: " + i);
}
label1: for (int x = 0; x < 5; x++) {
for (int y = 5; y > 0; y--) {
if (y == x) {
// 跳转到label1指向的外循环
break label1;
}
System.out.printf("(x,y) = (%d,%d)", x, y);
// 打印一个换行符,实现换行
System.out.println();
}
}
System.out.println("Game Over!");
}
}
输出结果:
Count is: 0
Count is: 1
Count is: 2
(x,y) = (0,5)
(x,y) = (0,4)
(x,y) = (0,3)
(x,y) = (0,2)
(x,y) = (0,1)
(x,y) = (1,5)
(x,y) = (1,4)
(x,y) = (1,3)
(x,y) = (1,2)
Game Over!
二、continue语句——终止当次循环,continue之后的语句不再执行,直接跳转到下一次循环中
continue \\不带标签
continue label \\带标签,label是标签名
public class HelloWorld {
public static void main(String[] args) {
int numbers[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (int i = 0; i < numbers.length; i++) {
if (i == 3) {
// 跳出循环
continue;
}
System.out.println("Count is: " + i);
}
label1: for (int x = 0; x < 5; x++) {
for (int y = 5; y > 0; y--) {
if (y == x) {
// 跳转到label1指向的外循环
continue label1;
}
System.out.printf("(x,y) = (%d,%d)", x, y);
// 打印一个换行符,实现换行
System.out.println();
}
}
System.out.println("Game Over!");
}
}
输出结果:
Count is: 0
Count is: 1
Count is: 2
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
(x,y) = (0,5)
(x,y) = (0,4)
(x,y) = (0,3)
(x,y) = (0,2)
(x,y) = (0,1)
(x,y) = (1,5)
(x,y) = (1,4)
(x,y) = (1,3)
(x,y) = (1,2)
(x,y) = (2,5)
(x,y) = (2,4)
(x,y) = (2,3)
(x,y) = (3,5)
(x,y) = (3,4)
(x,y) = (4,5)
Game Over!
网友评论