๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
BackEnd๐ŸŒฑ/Java

[Java] ์ด๋ฆ„ ๋ถ™์€ ๋ฐ˜๋ณต๋ฌธ(Labeled-Loop)

by dkswnkk 2022. 3. 13.

Labeled-Loop

Java์—์„œ๋Š” ๋ฐ˜๋ณต๋ฌธ์— ์ด๋ฆ„์„ ์ง€์ •ํ•ด์ฃผ์–ด ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์•„๋ž˜์˜ ์˜ˆ์‹œ ์ฝ”๋“œ๋ฅผ ๋ณด๋ฉฐ ๊ฐ„๋‹จํ•˜๊ฒŒ ์ •๋ฆฌํ•ด ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

public static void main(String[] args) {
        Loop1:
        for (int i = 1; i <= 2; i++) {
            System.out.println("์ฒซ ๋ฒˆ์งธ for๋ฌธ");
            for (int k = 1; k <= 10; k++) {
                if(k==3) break Loop1;
                System.out.println("๋‘๋ฒˆ์งธ for๋ฌธ");
            }
        }
    }
    
========์ถœ๋ ฅ ๊ฒฐ๊ณผ========
์ฒซ ๋ฒˆ์งธ for๋ฌธ
๋‘ ๋ฒˆ์งธ for๋ฌธ
๋‘ ๋ฒˆ์งธ for๋ฌธ

 ์ œ์ผ ์ตœ์ƒ์œ„ Loop์— Loop1์ด๋ผ๋Š” ์ด๋ฆ„์„ ์ง€์ •ํ•ด์ฃผ์—ˆ์Šต๋‹ˆ๋‹ค. ์›๋ž˜๋ผ๋ฉด break๋ฌธ์€ ๊ทผ์ ‘ํ•œ ๋‹จ ํ•˜๋‚˜์˜ ๋ฐ˜๋ณต๋ฌธ๋งŒ ๋ฒ—์–ด๋‚  ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์—, ๋‘ ๋ฒˆ์งธ for๋ฌธ๋งŒ ๋ฒ—์–ด๋‚˜์•ผ ํ•˜์ง€๋งŒ break Loop1์„ ํ†ตํ•ด ๋ฒ—์–ด๋‚˜์•ผ ํ•  ๋ฐ˜๋ณต๋ฌธ์„ ์ง€์ •ํ•ด์คŒ์œผ๋กœ์จ ์ตœ์ƒ๋‹จ ๋ฐ˜๋ณต๋ฌธ์„ ๋ฒ—์–ด๋‚˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค..

for๋ฌธ๊ณผ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ Loop๋ฌธ์—๋Š” ๋ชจ๋‘ ์ด๋ฆ„์„ ์ง€์ •ํ•ด ์ค„ ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— while๊ณผ do-while๋„ ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.

public class Test {
    public static void main(String[] args) {
        int cnt = 2;
        ์ด๋ฆ„์ž…๋‹ˆ๋‹ค:
        while (true) {
            System.out.println(cnt);
            while (true) {
                if (cnt == 2) break ์ด๋ฆ„์ž…๋‹ˆ๋‹ค;
            }
        }
    }
}

========์ถœ๋ ฅ ๊ฒฐ๊ณผ========
2

 

์ถ”๊ฐ€์ ์œผ๋กœ C++์—์„œ๋Š” naming loop๋ฅผ ์ง€์›ํ•˜์ง€ ์•Š๊ณ , goto๋ฌธ์„ ์‚ฌ์šฉํ•ด์„œ ํ•ด๋‹น ์กฐ๊ฑด๋ฌธ์„ ๋ฒ—์–ด๋‚˜๊ฒŒ ํ•  ์ˆ˜ ์žˆ๋Š”๋ฐ goto๋ฌธ์€ ๊ฑฐ์˜ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋‹ค์‹œํ”ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— C++์—์„œ๋Š” ์‚ฌ์šฉ์ด ํž˜๋“ค ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.(https://stackoverflow.com/questions/1257744/can-i-use-break-to-exit-multiple-nested-for-loops)

๋Œ“๊ธ€