0805.2024.Today I Learned

Sungju Kim·2024년 8월 5일

Sparta_Coding_Camp_TIL

목록 보기
10/53

Named Loops

Often times when you are using nested loops for your code, you have a condition where you need to break off from the ourter loop (either a for-loop or a while-loop). However, how do you tell the computer which loop you want to break out from? By default the code assumes you would like to break out from your inner most loop (in the current state) but this can be changed by labeling your loop and indicating in the 'break' which loop you want to break from.

Example

The outer most for-loop in this case is labeled 'outerLoop'.

public class LabeledLoops {
    public static void main(String[] args) {
        outerLoop:
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (i == 1 && j == 1) {
                    break outerLoop; // Break out of the outer loop
                }
                System.out.println("i: " + i + ", j: " + j);
            }
        }
    }
}
profile
Fully ✨committed✨ developer, always eager to learn!

0개의 댓글