Java语言中goto是保留关键字,没有goto语句,也没有任何使用goto关键字的地方。
Java中也可在特定情况下,通过特定的手段,来实现goto的功能。显然Java不愿意开发者随意跳转程序。下面解释两个特定:
特定情况:只有在循环体内,比如for、while语句(含do…while语句)中。
特定手段:语句标签和循环控制关键字break、continue,语法格式是:break/continue 语句标签。
1语句标签
语句标签在代码的某个位置做的一个标识,与break/continue一起使用可以达到跳到程序指定位置的作用。
2代码实现
public static void main(String[] args) {
outer: //外层循环标识
for (int i = 0; i < 10; i++) {
System.out.println("\nouter_loop:" + i);
inner: //内层循环标识
for (int k = 0; i < 10; k++) {
System.out.print(k + " ");
int x = new Random().nextInt(10);
if (x > 7) {
System.out.print(" >>x == " + x + ",结束inner循环,继续迭代执行outer循环了!");
continue outer; //继续执行outer标识的循环
}
if (x == 1) {
System.out.print(" >>x == 1,跳出并结束整个outer和inner循环!");
break outer; //跳出outer标识的循环
}
}
}
System.out.println("------>>>所有循环执行完毕!");
}
执行结果:
outer_loop:0
0 1 2 3 4 5 6 7 8 9 >>x == 8,结束inner循环,继续迭代执行outer循环了!
outer_loop:1
0 1 2 3 4 5 >>x == 9,结束inner循环,继续迭代执行outer循环了!
outer_loop:2
0 1 2 3 4 5 6 7 8 9 >>x == 8,结束inner循环,继续迭代执行outer循环了!
outer_loop:3
0 1 2 3 4 >>x == 9,结束inner循环,继续迭代执行outer循环了!
outer_loop:4
0 1 2 3 4 5 6 7 8 9 10 >>x == 8,结束inner循环,继续迭代执行outer循环了!
outer_loop:5
0 >>x == 1,跳出并结束整个outer和inner循环!------>>>所有循环执行完毕!
Process finished with exit code 0