简体   繁体   English

Java中的关键字循环有什么作用?

[英]What does the keyword loop in Java do?

public class Test 
{
        public void add(int a) 
        {
            loop: for (int i = 1; i < 3; i++)
            {
                    for (int j = 1; j < 3; j++) 
                    {
                        if (a == 5) 
                        {
                        break loop;
                        }
                        System.out.println(i * j);
                    }
            }
        }

        public static void main(String[] str)
        {
            Test t=new Test();
            t.add(4);s
        }
}

It's a shortcut for terminating both nested loops. 这是终止两个嵌套循环的捷径。 Citing the Branching Statements page from Java Tutorial: 引用Java教程中的Branching Statements页面

The break statement terminates the labeled statement; break语句终止带标签的语句; it does not transfer the flow of control to the label. 它不会将控制流转移到标签上。 Control flow is transferred to the statement immediately following the labeled (terminated) statement. 控制流紧接在标记(终止)的语句之后转移到该语句。

and

An unlabeled break statement terminates the innermost switch, for, while, or do-while statement, but a labeled break terminates an outer statement. 无标签的break语句终止for,while或do-while语句的最里面的开关,但是带标签的break终止外部的语句。

It's not a keyword, it's a label you choose. 它不是关键字,而是您选择的标签。 Just mark the external loop with labelName: ... . 只需用labelName: ...标记外部循环labelName: ... Then, you can nest loops and exit from them all by calling break labelName; 然后,您可以通过调用break labelName;来嵌套循环并从中退出break labelName; :

yourLabelName: for(int i = 0; i < 3; ++i) {
    for (int j = 0; j < 7; ++j) {
        break yourLabelName;
    }
}
// After calling break yourLabelName, you will end up here 

In your case, when a == 5 , then both loops are exited and the add() method terminates (returns). 在您的情况下,当a == 5 ,两个循环都退出,并且add()方法终止(返回)。

First of all this code will not compile as there is an s present in your code. 首先这个代码将无法编译,因为是s出现在你的代码。 t.add(4);s . t.add(4);s Remove s . 删除s After removing s your code output will be 1 2 2 4 . 删除s您的代码输出将为1 2 2 4 And loop is not a keyword but it is label expression in Java 循环不是keyword而是Java中的label expression

Its a label Syntax label语法

label strLabel:
//Labeled block of statements

It is possible to specify labels with break and continue 可以用breakcontinue指定标签

Mate, 伴侣,

loop is not any keyword in java. loop在Java中不是任何关键字。 Its a label. 它的标签。 Label are always used with break and continue to transfer the control flow. 标签始终会中断使用,并继续传递控制流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM