최원종의 개발 블로그

while문 본문

Java/자바 기본

while문

chl6698 2026. 2. 23. 16:44

while문은 주어진 조건이 참(true)인 동안 지정된 수행문을 반복적으로 수행하는 제어문.

조건이 맞지 않으면 반복하던 수행을 멈춤.

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

 

while문 이해

public class whileTest1 {
    //코드의 시작점

    public static void main(String[] args) {

        int i = 1;
        //괄호안에 조건식(true, false) - true인 동안 반복을 수행한다
        // i -- 1 --> 한번 반복
        // i -- 2 --> 두번 반복
        // i -- 3 --> 세번 반복
        // i -- 4 --> 반복 안함
        while (i <= 3) {
            //true 여기 구문 수행 됨.
            System.out.println("i 값 : " + i);

            //i++
            i = i + 1;

        }// end of while
        System.out.println("while 문 종료 후 i 값 확인 : " + i);
    }//end of main
}// end of class

 

 

while문 실습

public class whileTest2 {
    //코드의 시작점

    public static void main(String[] args) {
        // 1. 키보드에서 값을 받아서 1 부터 입력 받은 값 까지 출력하는 코드를 작성해 보자.
        // 2. 1 부터  10 까지 총 더한 값을 구하시오
        // 3. 1 + 2 + 3 ... + 10 = 55
        Scanner scanner = new Scanner(System.in);
        int start = 1;
        int end = scanner.nextInt();
        int sum = 0;

        System.out.println("입력 받은 값(로깅) " + end);
        // 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
        while (start <= end) {
            // 0 = 0 + 1 -- sum(1) = (1)
            // 1 = 1 + 2 -- sum(3) = (2)
            // 3 = 3 + 3 -- sum(6) = (3)
            // ...
            sum = sum + start;
            //System.out.println("start 값 확인 : " + start);
            start = start + 1;
        } // end of while
        System.out.println(" 총합 : " + sum);
    }//end of main
}// end of class

 

public class whileTest3 {

    //대문자로 시작하는 표기법 <-- 파스칼케이스
    public static void main(String[] args) {
        // 특정 조건을 만족하면 반복문을 멈추게 하는 기능을 만들어보자.
        Scanner sc = new Scanner(System.in);
        boolean flag = true;

        while (flag) {
            int a = sc.nextInt();
            System.out.println("a 값 확인 : " + a);
            //만약 a 값이 0이라면 반복문 종료
            if (a == 0) {
                flag = false;
            }

        }//end of while
        System.out.println("반복문 종료됨 ");
    }//end of main
}// end of class

 

while문 연습문제

 

1.메뉴선택 프로그램

package exercise;

import java.util.Scanner;

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

        //스캐너 사용을 선언
        Scanner sc = new Scanner(System.in);
        int choice;
        while (true) {
            System.out.println("\n메뉴선택");
            System.out.println("1.등록 2.조회 3.수정 4.삭제 0.종료");
            System.out.print("선택 : ");
            choice = sc.nextInt();

            if (choice == 1) {
                System.out.println("등록을 선택했습니다.");
            } else if (choice == 2) {
                System.out.println("조회를 선택했습니다.");
            } else if (choice == 3) {
                System.out.println("수정을 선택했습니다");
            } else if (choice == 4) {
                System.out.println("삭제을 선택했습니다");
            } else if (choice >= 5) {
                System.out.println("잘못된 입력입니다. 다시 선택해주세요");
            } else if (choice == 0) {
                System.out.println("프로그램을 종료합니다.");
                System.out.println("\n--------------------------");
                break;
            }
            System.out.println("\n--------------------------");
        }
    }// end of main
}// end of class

 

 

2.비밀번호 관리 시스템(심화)

package my;

import java.util.Scanner;

public class Ex04 {
    public static void main(String[] args) {
        //비밀번호 4자리를 입력받아 저장하는 기능 구현
        //비밀번호를 출력하는 기능을 구현
        //ex4 while 구문 형태 활용 및 응용
        Scanner sc = new Scanner(System.in);
        int choice;
        int password = 0;
        boolean flag = false;

        while (true) {
            System.out.println("\n--- 비밀번호 관리 시스템 ---");
            System.out.println("1. 비밀번호 등록 2.비밀번호 조회 0.종료");
            System.out.print("선택 : ");
            choice = sc.nextInt();
            if (choice == 1) {
                System.out.println("비밀번호 등록을 선택하셨습니다.");
                System.out.println("비밀번호를 입력해 주세요.");
                password = sc.nextInt();
                flag = true;
                System.out.println("비밀번호 등록이 완료되었습니다.");
            } else if (choice == 2) {
                if (flag == false){
                    System.out.println("먼저 비밀번호를 등록해주세요.");
                }else {
                    System.out.println("등록된 비밀번호는 " + password + " 입니다.");
                }


            } else if (choice == 0) {
                System.out.println("비밀번호 관리 시스템 종료");
                break;
            } else {
                System.out.println("잘못된 번호를 선택하셨습니다.");
                System.out.println(" 다시 선택해 주세요.");
            }
        }//end of while
    }//end of main
}//end of class

 

'Java > 자바 기본' 카테고리의 다른 글

break문, continun문  (0) 2026.02.23
Java(반복문)  (0) 2026.02.23
Java( 조건문)  (0) 2026.02.23
Java(연산자)  (1) 2026.02.18
Java(데이터 타입, 상수, 형 변환, 컴파일)  (0) 2026.02.12