1. while
while의 기본 구조
while(조건){
조건이 참이면 살행할 문장;
}
import java.util.Scanner;
public class Ex10_while {
public static void main(String[] args) {
// Ex01
System.out.println("==========Ex01==========");
int i;
for(i=1; i<=5; i++) {
System.out.println(i); // 5까지 출력후 반복문 나감
}
System.out.println("끝"); // 반복문을 나간 후 끝 출력
// Ex02
System.out.println("==========Ex02==========");
i=1;
while(i<=5) {
System.out.println(i);
i++;
}
System.out.println("while문 밖 : " + i);
// Ex03
System.out.println("==========Ex03==========");
int num;
Scanner input = new Scanner(System.in);
while(true) {
System.out.print("숫자 입력");
num = input.nextInt();
if (num<0) {
break; // //num에 입력한 숫자가 0보다 작으면(음수)일때 break
}
System.out.println("while 밖");
}
}
}
==========Ex01==========
1
2
3
4
5
끝
==========Ex02==========
1
2
3
4
5
while문 밖 : 6
==========Ex03==========
숫자 입력33
while 밖
2. break & continue
break
- **현재 반복문(또는 switch문)**을 즉시 종료하는 제어문
- 반복문의 조건식 검사 없이 바로 바깥으로 탈출
continue
- 현재 반복문의 이번 회차만 건너뛰고 다음 반복으로 진행
- 반복문은 종료되지 않고, 조건 검사 → 다음 반복으로 넘어감
public class Ex12_break_continue {
// Ex01 : break
public static void main(String[] args) {
for(int i=0; i<=10; i++) {
if(i==5)
break; // 5랑 같아지면 멈추기
System.out.print(i + " "); //0 1 2 3 4 ❤️
}
// 5랑 같아지면 반복문을 나옴(빠져나온 위치)
System.out.println("❤️");
System.out.println("============");
// Ex02 : continue
for(int i=0; i<=10; i++) {
if(i==5)
continue; // 5랑 같다면 바로아래 코드만 실행하지 말기 (5일때만 실행X)
System.out.print(i + " "); // 출력 : 0 1 2 3 4 6 7 8 9 10
}
}
}
사용 시 주의점
- break
- 중첩 반복문 안에서 사용하면 현재 속한 반복문만 종료
- 바깥 반복문까지 끝내고 싶으면 label(레이블) 사용
outer:
for (...) {
for (...) {
break outer; // 바깥 반복문까지 종료
}
}
- continue
- 현재 회차만 건너뛰므로, 무한 루프를 막기 위해 증감식/조건 변경 코드가 건너뛰어지지 않게 주의
💡 정리
- break → “여기서 끝”
- continue → “이번만 건너뛰고 계속”
- 조건 분기에 따라 둘을 적절히 조합하면 효율적인 반복문 제어 가능
'기초 및 언어 > ▶ Java&JSP' 카테고리의 다른 글
| 08. 정렬 (2) | 2025.08.14 |
|---|---|
| 07. 배열 (2) | 2025.08.14 |
| 00. Debug과정 (0) | 2025.08.13 |
| 05. 반복문 for (6) | 2025.08.13 |
| 04. 제어문 (4) | 2025.08.13 |