728x90

 

☕ while

- while은 반복문 중 하나다

- 컴퓨터가 잘하는 일은 반복하면서 일을 처리하는 것이다.

 

☕ while 사용법

- while문 탈출 조건식이 false를 반환할 때 while문을 종료하게 된다

변수의 초기호ㅕㅏ
while (탈출 조건식){
	탈출 조건식이 참일 경우 실행되는 코드;
    변수의 증감식;
}

 

☕ 예제 1

- 1부터 5까지 출력하세요

public class WhileExam1 {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 5) {
            System.out.println(i);
            i++;
        }
    }
}

 

 

☕ while문과 break

- while문에서 break를 만나면, 더 이상 반복하지 않는다. break는 보통 조건문 if와 함께 사용된다.

 

☕ 예제 2

- while(true){....} 는 무한루프라고 한다. 끝없이 반복한다.

- i가 11일 경우 while 블록을 빠져 나간다.

public class WhileExam2 {
    public static void main(String[] args) {
        int i = 1;
        while (true) {
            if(i == 11) break;
            System.out.println(i);
            i++;
        }
    }
}

 

☕ 예제 3 - while문과 후위증감식

- 변수 뒤에 후위 증가식이 붙을 경우 변수가 사용된 이후 값이 증가된다.

- i와 10를 한 후 1가 1 증가한다

public class WhileExam3 {
    public static void main(String[] args) {
        int i = 0;
        while (i++ <10) {
            System.out.println(i);
            }
    }
}

 

☕ 예제 4

- 1부터 10사이에 있는 짝수만 출력하시오

public class WhileExam4 {
    public static void main(String[] args) {
        int i = 0;
        while (i++ <10) {
            if(i%2 != 0)
                continue;
            System.out.println(i);
            }
    }
}
728x90

'개발&etc > JAVA' 카테고리의 다른 글

[java] 반복문 for  (0) 2023.03.08
[java] 반복문 do while  (0) 2023.03.08
[java] 조건문 Switch  (0) 2023.03.08
[java] 조건문과 삼항연산자  (0) 2023.03.08
[Java] 삼항연산자와 instanceof  (0) 2023.03.08