java

java 반복문 while

full-moon 2022. 2. 16. 16:57

예제

public class Main {

	public static void main(String[] args) {
			
//		int j = 1;
//		while(j <= 10) { //for처럼 반복횟수 정하기 가능함
//			System.out.println(j);
//			j++;
//			
//		}

		boolean run = true;
		
		while(run) {
			int dice = (int)(Math.random() * 6)+1; // 1~6까지 랜덤한 수 구하기
			if(dice == 5) {
            		//dice의 수가 5가 나오면 while의 조건이 false로 변하고 반복 종료
				run = false; 			
			}
			
			System.out.println("주사위값 : "+dice);
		}
	}

}

실행결과

설명

while    [반복문 while문 기본구조]
   반복횟수를 정하지 않고 사용할 때 사용

   while(반복조건){
     실행문;
     (증감식);
   }