iteration 반복문 (break, continue)

박성현·2024년 3월 14일

java

목록 보기
14/51

break문과 continue문을 추가적으로 실습해보자 ! !

먼저 break문을 실습해보자 !

  • break문을 사용하여 해당하는 반복문을 중지하고 빠져나온다.
  • switch문이나 무한반복문에는 필수로 사용해야한다.
package interationex;

public class BreakEx {

	public static void main(String[] args) {
		 // 중첩 반복문은 중지할 반복문의 이름을 주고 break
        for (int i=0; i<5; i++) {
            for (int j=0; j<5; j++) {
            	// j의 값이 3이상이 되면 break문으로 인해 2번째 for문을 빠져나갈 수 있음
                if (j==3) {
                    break;
                }
                System.out.println("i="+i+", j="+j);
            }
        }

    }

}

결과값 :


continue문 실습 !

  • for문에서는 증감식->조건식, while문에서는 조건식으로 이동
  • 짝수일 경우만 continue 실행한다.
package interationex;

public class BreakEx {

	public static void main(String[] args) {
		// 중첩 반복문은 중지할 반복문의 이름을 주고 break
		for (int i=0; i<5; i++) {
			if (i%2==0) {
				continue;
			}
			System.out.println(i);
		}
	}

}

결과값 :


1부터 100 사이의 랜덤한 1개의 숫자 맞추기

package interationex;

import java.util.Scanner;

public class OndRandomGame {

	public static void main(String[] args) {
		int com = (int)(Math.random()*100);
		Scanner sc = new Scanner(System.in);
		int cnt = 0;
		
		while(true) {
			cnt++;
			System.out.println("user >>");
			int user = sc.nextInt();
			if(com == user) {
				break;
			}
			if(user > com) {
				System.out.println("더 작아야해 !!");
			} else if (user < com) {
				System.out.println("더 커야해 !!");
			}
		}
		System.out.printf("%s회만에 성공해버렸어 !!",cnt);
	}

}

결과값 :

profile
개발기록장

0개의 댓글