JAVA(기본)

(JAVA) 반복문 while

mynote6676 2025. 4. 14. 17:24

학습 목표

 

-while문의 이해 그리고 for문과의 차이

-무한루프

 

범위가 애매할 경우 while문을 사용

 

조건이 참(true)인 동안 반복수행하기

● 주어진 조건에 맞는 동안(true) 지정된 수행문을 반복적으로 수행하는 제어문

● 조건이 맞지 않으면 반복하던 수행을 멈추게 됨

● 조건은 주로 반복 횟수나 값의 비교의 결과에 따라 true, false 판단 됨

 

package ch04;

public class WhileTest1 {
    public static void main(String[] args) {

        int i = 1;
        // 괄호안에 - 조건식 (true, false)
        while (i <= 3) {
            System.out.println(" i 값 : " + i);
            // while구문을 작성할 때 무한 루프를 조심하자 !
            //조건식에 처리가 없다면 무한히 반복한다.
            i = i + 1;
        }
        // 1회차 -출력, 에 값 1증가 , while (조건식 확인) - 1
        // 2회차 -출력, 에 값 1증가 , while (조건식 확인) - 2
        // 3회차 -출력, 에 값 1증가 , while (조건식 확인) - 3
        System.out.println("while 종료 후 i 값" + i);

    }//end of main
}// end of class

 

 

package ch04;

import java.util.Scanner;

public class WhileTest2 {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println("종료하고 싶은 정수값을 입력하시오 : ");

       // for 문 사용했을 때 1 ~10 까지의 총합 55
        // 위 내용을 while 구문으로 만들어서 출력
        int i = 1;
        int sum = 0;
        final int end = sc.nextInt();
            while(i < end){
                sum = sum + i ;
                // w조건식에 대한 처리를 잘 확인하자.
                i++;
            }
        System.out.println("sum : 총합 :" + sum);


    }//end of main
}// end of class

 

package ch04;

import java.util.Scanner;

public class WhileTest3 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        boolean flag = true; //깃발

        // 특정 조건이 만족한다면 flag =false
        while (flag) {
            int a = sc.nextInt();
            if(a == 0) {
                System.out.println("프로그램 종료");
                break;
            }
            System.out.print("...");
        }

    } //end of main
} // end of class