旧行李 2009-05-20 09:07 采纳率: 25%
浏览 415
已采纳

如何在 Java 中突破嵌套循环?

I've got a nested loop construct like this:

for (Type type : types) {
    for (Type t : types2) {
         if (some condition) {
             // Do something and break...
             break; // Breaks out of the inner loop
         }
    }
}

Now how can I break out of both loops. I've looked at similar questions, but none concerns Java specifically. I couldn't apply these solutions because most used gotos.

I don't want to put the inner loop in a different method.

Update: I don't want to rerun the loops, when breaking I'm finished with the execution of the loop block.

转载于:https://stackoverflow.com/questions/886955/how-to-break-out-of-nested-loops-in-java

  • 写回答

29条回答 默认 最新

  • 胖鸭 2009-05-20 09:11
    关注

    Like other answerers, I'd definitely prefer to put the inner loop in a different method. This answer just shows how the requirements in the question can be met.

    You can use break with a label for the outer loop. For example:

    public class Test {
        public static void main(String[] args) {
            outerloop:
            for (int i=0; i < 5; i++) {
                for (int j=0; j < 5; j++) {
                    if (i * j > 6) {
                        System.out.println("Breaking");
                        break outerloop;
                    }
                    System.out.println(i + " " + j);
                }
            }
            System.out.println("Done");
        }
    }
    

    This prints:

    0 0
    0 1
    0 2
    0 3
    0 4
    1 0
    1 1
    1 2
    1 3
    1 4
    2 0
    2 1
    2 2
    2 3
    Breaking
    Done
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(28条)

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况