[JAVA] While 반복문

박두팔이·2022년 11월 9일
0

While문

While문은 몇 번 반복을 해야할 지 정확히 모를 때 조건식이 참인동안 무한히 반복할때 사용한다.

  • while(조건식)
    : 괄호안의 조건식은 변수로 저장하여 외부에서 컨트롤이 가능할 수 있도록 설정하는 것이 좋다.

아래는 while문에서 3번 출력한 후 빠져나가는 코드작성이다.

public class While{
	public static void main(String[] args){
    	int count = 0;
    	while(count < 3) {
    		System.out.println("반복 실행 중");
            count++;
    	}
        System.out.println("while문 끝");
    }
}

while 예시2
또 다른 예로 사용자에게 입력을 받아 조건이 성립하면 while문을 종료하는 방법이 있다.

import java.util.Scanner;
public class While2 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		boolean ch = true;
		while(ch) {
			System.out.println("게임실행중 ");
			System.out.println("종료하시겠는가 Y/N");
			String input=sc.next();
			if(input.equals("Y")|| input.equals("y")) {
				System.out.println("게임을 종료합니다. ");
				ch = false;
			}
		}
		System.out.println("종료되었습니다 ");
		sc.close();
	}
}
profile
기억을 위한 기록 :>

0개의 댓글