본문 바로가기

StackOverflow

[Java] 중첩된 루프에서 빠져나가기

http://stackoverflow.com/questions/886955/breaking-out-of-nested-loops-in-java


Q: 중첩된 루프에서 빠져나가고 싶습니다.

저는 아래와 같은 중첩된 루프 구조를 하나 가지고 있습니다.

for (Type type : types) {
    for (Type t : types2) {
         if (some condition) {
             // 뭔가를 하거나 break를 함...
             break; // 내부 루프를 종료
         }
    }
}

두 루프 모두를 빠져나가려면 어떻게 해야 할까요? 몇 가지 다른 질문이 이미 있는 건 알지만, Java에 맞는 답은 없는 것 같습니다. 다른 답변은 goto를 써서 루프를 빠져나갔거든요.

제 내부 루프를 다른 함수로 분리하는 것도 원하지 않습니다.

수정: 루프 내에서 return을 하는 것도 원치않습니다. 

(질문자: boutta)



A: (수정: 다른 답변들 처럼, 내부 루프를 다른 메소드로 분리하는 걸 추천합니다. 이 답변은 질문에 있는 요구사항을 충족시키기 위해서만 작성 된 것입니다.)

label과 break를 조합해서 이 요구사항을 충족시킬 수 있습니다.


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

(답변자: Jon Skeet)

(역주: 그 유명한 Jon Skeet입니다! 이분 reputation을 보세요!)


_

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.

shareeditflag

_

1320down voteaccepted

(EDIT: 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
shareeditflag