java - 关于 Java 中的标签表现得像 GOTO

标签 java goto

这不应该无限循环吗?

someLabel:{
        for (int i = 0; i < 5; ++i) {
            System.out.println(i);
            if (i == 3)
                break someLabel;
        }
}

开始了

0
1
2
3

然后死了。我正在阅读有关 Java 中 GOTO 替代方法的问题。这是公认的答案:https://stackoverflow.com/a/2430789/555690 . for循环是不是应该再执行一次?

最佳答案

来自 http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html :

The break statement terminates the labeled statement; it does not transfer the flow of control to the label. Control flow is transferred to the statement immediately following the labeled (terminated) statement.

除了我从未见过任何使用这种控制流的真实代码之外,我猜它的用途是从内循环中断开外循环(如提供的链接中所述):

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;
            }
        }
    }

关于java - 关于 Java 中的标签表现得像 GOTO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24543955/

相关文章:

java - 在 Eclipse 中自定义搜索(文件)功能

java - Hibernate多对多关系

java - 我将如何根据另一个 ArrayList 的行为对 ArrayList 进行排序? ( java )

java - HttpURLConnection:发送 10,000 个请求给出 "Connection reset"

java - 如何计算位于给定数组的两个元素之间的数组元素的数量

loops - Perl循环标签算作GOTO吗?

c - c编程中goto的替代方案

c - 使用 'goto' 的流量控制宏

c# - c# 中的 goto 语句慢吗?

g++ - 语句goto不能跨变量定义?