请解释一下Labeled statements的用法

发布于 2024-08-30 23:01:37 字数 108 浏览 11 评论 0 原文

  • Java 中标记语句的唯一用途是中断和继续吗?
  • 您什么时候在程序中使用过标签语句?

抱歉,代码片段已被删除。我正在拆分问题

  • Is breaking and continuing the only uses of labeled statements in Java?
  • When have you used Labeled Statements in your programs?

Sorry the code snippet has been deleted. I am splitting the question

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

烧了回忆取暖 2024-09-06 23:01:37

JLS 14.7 标记语句

(为了清晰起见进行了编辑)

语句可以有标签前缀(标识符语句)。 标识符被声明为直接包含的语句的标签。

与 C 和 C++ 不同,Java 编程语言没有 goto 语句;标识符语句标签与 break 一起使用 (§14.15)或继续§14.16) 出现在带标签的语句中任何位置的语句。

因此,JLS 很清楚,标签与 breakcontinue 一起使用,并且 Java 编程语言的其他语法元素都没有使用它。

严格来说,breakContinue,无论是否标记,都永远是必要的。它们总是可以从代码中写出来。然而,按照惯用方式使用它们可以产生更具可读性的代码。


下面是一个说明性示例:给定一个 int[],我们希望:

  • print "One (1)" on 1
  • print " 2 上的两 (2)"
  • 0 上打印 “零”
  • 立即停止对任何其他数字的处理

    int[] arr = { 1, 2, 0, 1, -1, 0, 2 };
    环形:
    for (int num : arr) {
        开关(数字){
        案例1:
            System.out.print("一");
            休息;
        案例2:
            System.out.print("两个");
            休息;
        案例0:
            System.out.print("零");
            继续循环;
        默认:
            打破循环;
        }
        System.out.print("(" + num + ") ");
    }
    // 打印“一(1)二(2)零一(1)”
    

我们可以看到:

  • 不同的数字在 switch 中处理 switch
  • switch 中未标记 break 用于避免 case 之间的“失败”
  • 标记为 Continue Loop; 用于跳过 case 0: 的后处理(该标签不是必需的)此处)
  • 标记为 break loop; 用于终止 default: 上的循环(此处标签;否则它是一个 switch break)

因此标记为 break/continue 也可以在嵌套循环之外使用;当 switch 嵌套在循环内时可以使用它。更一般而言,当可能存在多个 break/continue 目标,并且您想要选择一个不立即包含 break/ 的目标时,会使用它继续语句。


这是另一个例子:

    morningRoutine: {
        phase1: eatBreakfast();
        if (grumpy) break morningRoutine;
        phase2: kissWife();
        phase3: hugChildren();
    }
    http://stackoverflow.com is the best website ever!

这是另一种情况,标记的 break 不是在迭代语句中使用,而是在简单的块语句中使用。有人可能会争辩说,标签可以提高可读性。这一点是主观的。

不,最后一行不会给出编译时错误。它实际上是受到 Java Puzzlers Puzzle 22:Dupe of URL 的启发。不幸的是,这个难题并没有更深入地“正确”使用标记语句。

JLS 14.7 Labeled statements

(edited for clarity)

Statements may have label prefixes (Identifier : Statement). The Identifier is declared to be the label of the immediately contained Statement.

Unlike C and C++, the Java programming language has no goto statement; identifier statement labels are used with break (§14.15) or continue (§14.16) statements appearing anywhere within the labeled statement.

So the JLS is clear that labels are used with break or continue, and no other grammatical element of the Java programming language uses it.

Strictly speaking, break and continue, labeled or not, are NEVER necessary. They can always be written out of the code. Used idiomatically, however, they can lead to more readable code.


Here's an illustrative example: given an int[], we want to :

  • print "One (1)" on 1
  • print "Two (2)" on 2
  • print "Zero " on 0
  • immediately stop processing on any other number

    int[] arr = { 1, 2, 0, 1, -1, 0, 2 };
    loop:
    for (int num : arr) {
        switch (num) {
        case 1:
            System.out.print("One ");
            break;
        case 2:
            System.out.print("Two ");
            break;
        case 0:
            System.out.print("Zero ");
            continue loop;
        default:
            break loop;
        }
        System.out.print("(" + num + ") ");
    }
    // prints "One (1) Two (2) Zero One (1) "
    

Here we see that:

  • The different numbers are processed in a switch
  • Unlabeled break in the switch is used to avoid "fall-through" between cases
  • Labeled continue loop; is used to skip post-processing on case 0: (the label is not necessary here)
  • Labeled break loop; is used to terminate the loop on default: (the label is necessary here; otherwise it's a switch break)

So labeled break/continue can also be used outside of nested loops; it can be used when a switch is nested inside a loop. More generally, it's used when there are potentially multiple break/continue target, and you want to choose one that is not immediately enclosing the break/continue statement.


Here's another example:

    morningRoutine: {
        phase1: eatBreakfast();
        if (grumpy) break morningRoutine;
        phase2: kissWife();
        phase3: hugChildren();
    }
    http://stackoverflow.com is the best website ever!

Here's another case of a labeled break being used not within an iterative statement, but rather within a simple block statement. One may argue that the labels lead to better readability; this point is subjective.

And no, the last line DOES NOT give compile time error. It's actually inspired by Java Puzzlers Puzzle 22: Dupe of URL. Unfortunately, the puzzle does not go into "proper" use of labeled statements in more depth.

弄潮 2024-09-06 23:01:37

是的,breakcontinue 是 Java 中标记语句的唯一两种用途。 (Java 没有 goto 语句。)

您可以使用标签来打破嵌套循环。

outer:
    for (int i = 0; i < 5; i++) {    
        for (int j = 0; j < 5; j++) {
            System.out.println("Hello");
            continue outer;
        } // end of inner loop
        System.out.println("outer"); // Never prints
    }
System.out.println("Good-Bye");

当您继续回到outer标签时,您将跳过内部循环和外部循环的其余部分,包括 print 语句。

Yes, break and continue are the only two uses for labeled statements in Java. (Java has no goto statement.)

You can use a label to break out of nested loops.

outer:
    for (int i = 0; i < 5; i++) {    
        for (int j = 0; j < 5; j++) {
            System.out.println("Hello");
            continue outer;
        } // end of inner loop
        System.out.println("outer"); // Never prints
    }
System.out.println("Good-Bye");

When you continue back to the outer label, you're skipping the remainder of both the inner and the outer loop, including the print statement.

荭秂 2024-09-06 23:01:37
search:
    for (i = 0; i < arrayOfInts.length; i++) {
        for (j = 0; j < arrayOfInts[i].length; j++) {
            if (arrayOfInts[i][j] == searchfor) {
                foundIt = true;
                break search;
            }
        }
    }
search:
    for (i = 0; i < arrayOfInts.length; i++) {
        for (j = 0; j < arrayOfInts[i].length; j++) {
            if (arrayOfInts[i][j] == searchfor) {
                foundIt = true;
                break search;
            }
        }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文