Java标签用法 [英] Java Label usage

查看:372
本文介绍了Java标签用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过java好文章,我发现这样的代码完美编译。

Somewhere going through java good articles, I found that such code compiles perfectly.

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

说明 http: word将被视为标签, // www.google.com 作为评论

description says that http: word will be treated as label and //www.google.com as comment

我没有得到Java Label如何在循环外使用?
在什么情况下应该使用Java Label外部循环?

I am not getting how Java Label is useful outside loop? Under what situation Java Label outside loop should be used?

推荐答案

以下是在Java中使用标签的一个好处:

Here is one benefit of using labels in Java:

block:
{
    // some code

    if(condition) break block;

    // rest of code that won't be executed if condition is true
}

嵌套循环的另一种用法:

Another usage with nested-loops:

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
}

这篇关于Java标签用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆