Java
반복문( while )
햄발자
2024. 4. 12. 15:03
while문
수행문을 수행하기 전 조건을 체크하고 그 조건의 결과가 true인 동안 반복 수행
조건이 참(true) 인 동안 반복수행하기
- 주어진 조건에 맞는 동안(true) 지정된 수행문을 반복적으로 수행하는 제어문
- 조건이 맞지 않으면 반복하던 수행을 멈추게 됨
- 조건은 주로 반복 횟수나 값의 비교의 결과에 따라 true, false 판단 됨
예시
package basic.ch04;
public class WhileTest1 {
// 코드의 시작점
public static void main(String[] args) {
// 1 부터 10 까지 콘솔창에 숫자를 출력하소 싶어!
// System.out.println(1);
// System.out.println(2);
// System.out.println(3);
// System.out.println(4);
// System.out.println(5);
// System.out.println(6);
// System.out.println(7);
// System.out.println(8);
// System.out.println(9);
// System.out.println(10);
// x <= 10
int i = 1;
while( i <= 10) {
System.out.println(i);
// while 구문은 조건식에 처리가 없다면 무한이 반복한다.
i++;
//i = i + 1;
//i += 1;
} // end of while
} // end of main
} // end of clas
예시
package basic.ch04;
public class whileTest2 {
// 코드의 시작점(메인함수)
public static void main(String[] args) {
// 특정 조건일 때 반복문을 종료 시켜 보자.
boolean flag = true; // 깃발
int start = 1;
int end = 3;
while (flag) {
if (start == end) {
System.out.println("if 구문이 동작함");
flag = false;
return;
}
System.out.println("start : " + start);
start++;
} // end of while
} // end of main
} // end of class