在查看一些关于Java的好文章时,我发现以下代码可以完美编译。
public int myMethod(){
http://www.google.com
return 1;
}
描述说明http:
这个词将被视为标签,//www.google.com
将被视为注释。
我不明白Java标签在循环外有什么用处? 在什么情况下应该使用循环外的Java标签?
在查看一些关于Java的好文章时,我发现以下代码可以完美编译。
public int myMethod(){
http://www.google.com
return 1;
}
描述说明http:
这个词将被视为标签,//www.google.com
将被视为注释。
我不明白Java标签在循环外有什么用处? 在什么情况下应该使用循环外的Java标签?
使用Java标签的一个好处如下:
block:
{
// some code
if(condition) break block;
// rest of code that won't be executed if condition is true
}
嵌套循环的另一种用法:
outterLoop: for(int i = 0; i < 10; i++)
{
while(condition)
{
// some code
if(someConditon) break outterLoop; // break the for-loop
if(anotherConditon) break; // break the while-loop
// another code
}
// more code
}
或者:
outterLoop: for(int i = 0; i < 10; i++)
{
while(condition)
{
// some code
if(someConditon) continue outterLoop; // go to the next iteration of the for-loop
if(anotherConditon) continue; // go to the next iteration of the while-loop
// another code
}
// more code
}
continue outterLoop
是没有意义的,因为你可以在那里使用一个简单的 break
。这只有在更深层次的循环中才有意义。或者我完全错了吗? - WarrenFaith只因編譯成功並不代表它有用......
在Java中,標籤通常被忽視了(誰使用帶有標籤的 break
和 continue
...?)。但是,僅僅因為標籤沒有被使用並不代表它是非法的。