Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java标签用法_Java - Fatal编程技术网

Java标签用法

Java标签用法,java,Java,在阅读java优秀文章时,我发现这样的代码编译得非常完美 public int myMethod(){ http://www.google.com return 1; } 说明中说,http:word将被视为标签,//www.google.com将被视为注释 我不明白Java标签在循环外是如何有用的? 在什么情况下应该使用Java标签外部循环?在Java中使用标签有一个好处: block: { // some code if(condition) break

在阅读java优秀文章时,我发现这样的代码编译得非常完美

public int myMethod(){
    http://www.google.com
    return 1;
}
说明中说,
http:
word将被视为标签,
//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(条件)
{
//一些代码
if(someConditon)break-outterLoop;//中断for循环
if(anotherConditon)break;//中断while循环
//另一个代码
}
//更多代码
}
或:

outterLoop:for(int i=0;i<10;i++)
{
while(条件)
{
//一些代码
if(someConditon)continue outterLoop;//转到for循环的下一次迭代
如果(其他条件)继续;//转到while循环的下一次迭代
//另一个代码
}
//更多代码
}

仅仅因为它可以编译并不意味着它是有用的


标签在Java中经常被忽略(谁使用标签的
break
continue
?)。但是,仅仅因为没有使用标签并不意味着它是非法的。

您使用
continue outterLoop
的第二个示例是毫无意义的,因为您可以在那里使用一个简单的
中断。这在更深的循环中是有意义的。还是我完全错了?@Warrenfith你是对的。更新了答案。该死的,没关系,遗漏了一些东西:d如果while循环之后仍然有代码在for循环中,那么前面的示例就不会毫无意义了。@Math你是对的。更新了答案;)如果可以避免,则不应在循环之外使用。无论如何,这不是java思维的一部分,因为它引入了复杂性。就像在一个函数中有多个返回。
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
}