JAVA/조건문과 반복문

반복문 - while, do~while

Lune Bleue 2019. 12. 14. 01:04

1. while 

 

표현식

while(조건식){

수행할 문장

[증감식 or 분기문]

}

 

while문 의 경우 역시 for문과 같이 조건식이 true이면 while문 안에있는 수행할 문장이 수행된다. 조건식에 들어가는 변수는 while문 밖에서 선언 및 초기화 해서 사용하게 된다.

 

int a = 0;
while( a <5){  ->조건식
    System.out.print( a + " ");
    a++;  ->증감식
}; -> 0 1 2 3 4

 

 

while 조건식은 숫자 뿐만 아니라 문자/ 문자열이 가능하며, java.util.Scanner 클래스를 import하여 입력값을 받아 사용 할 수 있다.

 

문자의 경우

Scanner sc = new Scanner(System.in); -> 문자를 입력 받기 위해 Scanner 객체를 생성.

 

char a = ' '  ;   ->  null(값없음)으로 초기화
while( a != 'c'){  -> 변수 a의 값이 c가 아니면 무한하게 돌게된다.
          System.out.print("a의 값을 입력해주세요 : ");
          a= sc.next().charAt(0); -> char 자료형을 받아 a에 저장한다..
          System.out.println(a);
    }
System.out.println("while문 종료");
}  

 

불린값의 경우 밖에서 선언 할 필요없이 조건식에 넣을 수 있으며, true를 넣을 경우에는 break문이 없는한 계속 돌게 된다.

 

while(true){

    System.out.print( "a" + "  ");

} -> a a a a a a a a a a a a a ......

 

위와 같은 경우를 방지하기 위해서 조건절과 break문을 사용하여 강제로 빠져 나오게 할 수있다. 

int num =0

while(true){

    System.out.print( "a" + "  ");

    num++

    if(num == 3){

        break;

    }

} -> a a

 

 

continue의 경우 조건식으로 다시 이동하게 된다.

int a = 0; 
while( a <5){ 

  a++; 

  if(a == 2){

          continue;

    }

    System.out.print( a + " "); 
    

}; -> 1,3,4,5

 

이 경우 만약  증감식이 continue문 아래에 있을경우 a가 2일때 계속 조건식으로 가기 때문에 0과 1만 출력후 무한히 돌게되어 주의해야 한다.

 

while문 또한 for문처럼 중첩 사용이 가능하다.

 

int dan = 2; 
while(dan < 10) {
    int j = 1;
    if(dan %2 ==0) {
        System.out.println("****"+dan+"단****");
        while(j <= 9){
            System.out.println(dan +" * " +j +" = " +dan*j);
             j++;
        }
      }
dan++;
System.out.println();
}

 

2. do~while

 

표현식 

do{

실행할 문장

}while(조건);

 

do~while문의 경우 while문과 동일하나, 조건식이 false여도 반드시 한번은 실행한다는 점이 다르다.

 

int a = 0; 
do{  
    System.out.print( a + " "); 
    a++; 
}while( a <5); -> 0 1 2 3 4

 

false일 경우

do{  
    System.out.print( a + " "); 
    a++; 
}while( a >5); -> 0 

 

while문의 경우 조건식이 처음 false면 실행하지 않는다.