gpt4 book ai didi

java - 打破标签不给标签带来控制

转载 作者:行者123 更新时间:2023-12-04 20:50:56 25 4
gpt4 key购买 nike

我是 Java 的新手,正在为 OCA 做准备。我正在尝试使用 break 和 continue 标签。根据指南中的描述,似乎既有标签,也只是将控件带到标签上。但是使用测试代码既不会在 break 标签为较早行时抛出错误,也不会从标签开始执行。

虽然我永远不会使用 break 和 continue 标签。但从考试的角度理解它很重要。

示例代码:

public class B{
public static void main(String[] args){
int i = 0;

label1: for(;i<=10;i++){
System.out.println(i);
if(i==4)
continue label1;
}
System.out.println("out" + i);

i=0;
label2: for(;i<=10;i++){
System.out.println(i);
if(i==4)
break label2;
}
System.out.println("out" + i);
}

}

结果:

java B
0
1
2
3
4
5
6
7
8
9
10
out11
0
1
2
3
4
out4

为什么 break 不从 label 继续执行?

还包括指南书中的摘录:

excerpt

我从 Yassir 的回答中的例子中理解:

标签后面应该有一个 block 。

continue 在 block 的开头带来控制,break 在结尾带来控制。谢谢

最佳答案

这两种说法是有区别的。

Break (JLS §14.15)

A break statement transfers control out of an enclosing statement.

Continue (JLS §14.16)

[...] Control passes to the loop-continuation point of an iteration statement.


例子

下面是两个非常简单的例子,在现实生活中一点用处都没有,只是为了演示使用不同语句的 Action 。

// This will print "continue" forever.
CONTINUE_LOOP:
while(true) {
System.out.println("continue");
continue CONTINUE_LOOP;
}

// This will only print "break" once and then break out of the loop
BREAK_LOOP:
while(true) {
System.out.println("break");
break BREAK_LOOP;
}

关于java - 打破标签不给标签带来控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36359317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com