【问题标题】:Java Label usage [duplicate]Java标签使用[重复]
【发布时间】:2013-11-07 12:54:53
【问题描述】:

某处翻阅java好文章,发现这样的代码编译完美。

public int myMethod(){
    http://www.google.com
    return 1;
}

描述说http:这个词会被当作标签,//www.google.com会被当作评论

我不知道 Java 标签在循环外有什么用处? 什么情况下应该使用Java Label outside loop?

【问题讨论】:

  • 如果可以避免,它不应该在循环之外使用。无论如何,它不是 Java 思维方式的一部分,因为它引入了复杂性。就像在一个函数中有多个返回一样。

标签: java


【解决方案1】:

这是在 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 你是对的。更新了答案。
  • 该死,没关系,错过了什么:D
  • 如果在while循环之后还有代码还在for循环里面的话,前面的例子就完全没有意义了。
  • @Math 你是对的。更新了答案;)
【解决方案2】:

仅仅因为它编译并不意味着它有用.....

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-02
    • 1970-01-01
    • 2018-06-27
    • 2011-05-24
    • 2014-05-16
    • 1970-01-01
    • 2015-07-12
    相关资源
    最近更新 更多