为什么要给 If 语句命名?
我刚刚发现我可以为 For 和 While 语句命名。我知道如果您想中断或继续特定循环,它很有用。
但我为什么要给 If 起个名字呢?它看起来没什么用
name: if(true){
//do something
}
这编译没有问题
I just discovered that i can give a name to For and While statements. I understand that it is useful if you want to break or continue a specific loop.
But why should i give a name to an If?? It looks useless
name: if(true){
//do something
}
This compiles without problems
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果你有一个带有名称的代码块,你可以使用break来退出它,这就是我发现的命名块的用途。
它也可以在没有 if 的情况
下工作:在我的工作中,当某些逻辑上有一组守卫条件,而无论守卫的结果如何,另一组逻辑都会落入其中时,就会出现这种情况。
另一个例子是,替代结构更难以阅读和修改:
尽管通常我使用裸块而不是 if。
If you have a code block with a name, you can use break to exit it, that is the use I have found for naming blocks.
it also works without the if:
This comes up in my work when there are a set of guard conditions on some logic, and another set of logic that will be fallen down into regardless of the outcome of the guards.
A further example where alternative structures are more difficult to read and modify:
though usually I use a bare block and not an if.
您可以在任何语句块之前使用标签。这可能是最常用的 for 循环,但在其他地方也完全有效。
You can use labels before any statement block. This is maybe most commonly used for loops, but is perfectly valid elsewhere.
莎拉·快乐答案实际上比我的更正确,它表明除了循环之外,您还可以使用
break
来破坏代码块,所以我建议查看她的答案。这确实是一个 标签,正如您所说的那样For 和 While 循环。它在其他地方也有效,但我想补充一点,你不能使用
虽然
goto
是一个保留字,但Java不支持goto,但它确实以标记循环与break
和continue
相结合的形式支持它。如果您扩展代码示例以包含 goto,例如:
您会收到错误,指出
表达式非法开始
和不是语句
或者,如果您尝试使用
继续
你的标签,但没有循环,例如:你会得到
undefined label: name
所以就编译器而言,有一个没有循环的标签是可以的,但如果没有循环,它几乎毫无价值。
Sarah Happy's answer is actually more correct than mine in showing that you can use
break
to break code blocks, in addition to loops, so I suggest looking at her answer.That is indeed a label, which as you said is for For and While loops. It is valid elsewhere, but I'd like to add that you cannot use
While
goto
is a reserved word, Java does not support goto, but it does support it in the form of labeled loops coupled withbreak
andcontinue
.If you expanded your code sample to include a goto, like:
You'd get errors, saying both
illegal start of expression
andnot a statement
Alternatively, if you tried to use
continue
with your label, but without a loop, like:You'd get
undefined label: name
So in terms of the compiler, having a label without a loop is ok, but it's pretty much worthless without a loop.
就像打破循环一样,您可能想跳回或跳转到 if 语句。尽管每当您开始考虑这一点时,请考虑创建一种新方法。
Just like breaking a loop you might want to jump back or toward an if statement. Although whenever you start thinking about this, look into creating a new method instead.