새소식

Java/제대로 파는 자바

[제대로 파는 자바 (Java)-by 얄코] while & do while

  • -

해당 게시물은 [제대로 파는 자바 (Java) - by 얄코]를 수강한 내용을 바탕으로 작성하였습니다.

 

 

 

while : 조건이 true일 동안 반복 수행

int i = 0;  //변수 초기화

//  💡 while 문의 괄호에는 종료조건만!
while (i < 10) {
    // 종료조건 충족을 위한 값 변화는 외적으로
    System.out.println(i++);
}

 

//  💡 의도적인 무한 루프에 널리 쓰이는 코드
while (true) {
    System.out.println("인간의 욕심은 끝이 없고");
    System.out.println("같은 실수를 반복한다.");
}

 

double popInBillion = 7.837;

//  ⭐️ break 를 통한 반복 탈출
while (true) {
    System.out.println("세계인구: " + (popInBillion -= 0.1));
    if (popInBillion <= 0) break;

    System.out.println("인간의 욕심은 끝이 없고");
    System.out.println("같은 실수를 반복한다.");
}

System.out.println("인류 멸종");

 

        //  100보다 작은 3의 배수들 출력해보기

//        int i = 1;
//
//        // ⚠️ 의도대로 작동하지 않음. 이유는?
//        while (true) {
//            if (i % 3 != 0) continue;  // 🔴
//            //continue때문에 밑코드를 실행하지 못하므로 i계속1인 무한루프
//            System.out.println(i);
//
//            if (i++ == 100) break;
//        }



        // 작동되는 코드지만 가독성이 좋진 않음
//        int i = 1;
//
//        while (true) {
//            if (i++ == 100) break;
//            if ((i - 1) % 3 != 0) continue;
//
//            System.out.println(i - 1);
//        }




        int i = 1;

        //  보다 가독성을 높이고 의도를 잘 드러낸 코드
        while (true) {
            int cur = i++;

            if (cur == 100) break;
            if (cur % 3 != 0) continue;

            System.out.println(cur);

        }

 

 

 

do ... while : 일단 수행하고 조건을 봄

int enemies = 0;

System.out.println("일단 사격");

do {
    System.out.println("탕");
    if (enemies > 0) enemies--;
} while (enemies > 0);

System.out.println("사격중지 아군이다");

 

 

 

int x = 11; // 10 이상으로 바꿔서 다시 실행해 볼 것
int y = x;

while (x < 10) {
    System.out.println("while 문: " + x++);
}

do {
    System.out.println("do ... while 문: " + y++);
} while (y < 10);

 

 

 

중첩 예제

int lineWidth = 5;

while (lineWidth > 0) {
    int starsToPrint = lineWidth--;
    while (starsToPrint-- > 0) {
        System.out.print("*");
    }
    System.out.println();  //줄바꿈
}



//  for 문으로 다시 작성
for (int i = 5; i > 0; i--) {
    for (int j = i; j > 0; j--) {
        System.out.print("@");
    }
    System.out.println();
}

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.