Java - switch문과 while문 학습 정리

My Pale Blue Dot·2025년 2월 27일
0

JAVA

목록 보기
6/35
post-thumbnail

📅 날짜

2025-02-27

📌 학습 내용

자바의 제어문 중 switch 문과 while 문을 학습하고, 이를 활용한 다양한 예제를 실습하였습니다.
제어문은 프로그램의 흐름을 조정하는 중요한 개념이며, 이를 잘 활용하면 코드의 가독성과 효율성을 높일 수 있습니다.
이번 학습에서는 다음과 같은 개념을 배웠습니다.


1️⃣ switch

switch 문은 하나의 변수 값을 여러 개의 경우(case)와 비교하여 실행할 코드를 선택할 때 사용됩니다.
이는 if-else 문보다 가독성이 뛰어나고, 특정 값에 따른 분기 처리를 할 때 유용합니다.

🔹 기본 구조

switch (변수) {
    case1:
        // 실행 코드
        break;
    case2:
        // 실행 코드
        break;
    default:
        // 모든 case에 해당하지 않는 경우 실행
}

🔹 주요 특징

  • case 뒤에는 상수 값만 올 수 있으며, 변수나 조건식은 사용할 수 없음.
  • break 문을 사용하지 않으면 다음 case가 연속 실행됨 (fall-through).
  • default는 모든 case에 해당하지 않을 때 실행되며 생략 가능함.

🔹 예제 코드 - 메달 색상 출력

import java.util.Scanner;

public class SwitchExample {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("등수를 입력하세요: ");
        int ranking = sc.nextInt();
        char medalColor;

        switch (ranking) {
            case 1:
                medalColor = 'G';
                System.out.println("🏅 금메달(Gold)");
                break;
            case 2:
                medalColor = 'S';
                System.out.println("🥈 은메달(Silver)");
                break;
            case 3:
                medalColor = 'B';
                System.out.println("🥉 동메달(Bronze)");
                break;
            default:
                medalColor = 'C';
                System.out.println("🎖️ 참여상(Challenge Medal)");
        }

        System.out.println(ranking + "등의 메달 색상은 " + medalColor + "입니다.");
    }
}

📌 실행 예시

등수를 입력하세요: 2
🥈 은메달(Silver)
2등의 메달 색상은 S입니다.

2️⃣ while

while 문은 조건이 true인 동안 반복해서 실행되는 반복문입니다.
반복 횟수가 정해져 있지 않거나, 특정 조건을 만족할 때까지 반복할 경우 유용하게 사용할 수 있습니다.

🔹 기본 구조

while (조건식) {
    // 반복 실행할 코드
}

🔹 주요 특징

  • 조건이 false가 될 때까지 반복 실행됨.
  • 무한 루프를 방지하기 위해 반복문 내부에서 조건을 변경하는 코드가 필요함.
  • break를 사용하면 강제로 while 문을 탈출할 수 있음.

🔹 예제 1 - "HELLO WORLD" 10번 출력

public class WhileExample {
    public static void main(String[] args) {
        int i = 0;
        while (i < 10) {
            System.out.println("HELLO WORLD");
            i++;
        }
    }
}

📌 실행 결과

HELLO WORLD
HELLO WORLD
(반복 10회)

🔹 예제 2 - 1부터 10까지의 합 구하기

public class SumExample {
    public static void main(String[] args) {
        int i = 1;
        int sum = 0;

        while (i <= 10) {
            sum += i;
            i++;
        }

        System.out.println("1부터 10까지의 합: " + sum);
    }
}

📌 실행 결과

1부터 10까지의 합: 55

🔹 예제 3 - N부터 M까지의 합 구하기 (N > M이면 교환)

import java.util.Scanner;

public class SumNM {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("시작 숫자 N 입력: ");
        int n = sc.nextInt();
        System.out.print("끝 숫자 M 입력: ");
        int m = sc.nextInt();

        if (n > m) {
            int temp = n;
            n = m;
            m = temp;
        }

        int i = n, sum = 0;
        while (i <= m) {
            sum += i;
            i++;
        }

        System.out.println(n + "부터 " + m + "까지의 합: " + sum);
    }
}

🔹 예제 4 - 구구단 출력 (2 ≤ N ≤ 9)

import java.util.Scanner;

public class Gugudan {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n;

            // 유효한 입력값 받기
    System.out.print("출력할 구구단 (2~9) 입력: ");
    n = sc.nextInt();
    
    while (n < 2 || n > 9) {
        System.out.println("구구단의 범위는 2 - 9 사이값을 입력하셔야됩니다");
        System.out.print("출력할 구구단 (2~9) 입력: ");
        n = sc.nextInt();
    }

    int i = 1;
    while (i <= 9) {
        System.out.printf("%d x %d = %d\n", n, i, n * i);
        i++;
    }
}

📌 실행 결과 (예: 5단)

출력할 구구단 (2~9) 입력: 5
5 x 1 = 5
5 x 2 = 10
...
5 x 9 = 45

더 길고 자세한 벨로그 포스트를 만들어줄게! 😊
이전에 올려준 코드들을 기반으로 개념 설명을 추가해서 좀 더 풍부한 내용을 정리했어.


🔹 예제 5 - N부터 M까지 수(N<M) 중 짝수와 홀수의 합 구하기

import java.util.Scanner;

public class SumEvenOdd {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("시작 숫자 N 입력: ");
        int n = sc.nextInt();
        System.out.print("끝 숫자 M 입력: ");
        int m = sc.nextInt();

        if (n >= m) {
            int temp = n;
            n = m;
            m = temp;
        }

        int i = n;
        int evenSum = 0, oddSum = 0;
        while (i <= m) {
            if (i % 2 == 0) {
                evenSum += i;
            } else {
                oddSum += i;
            }
            i++;
        }

        System.out.println("짝수 합: " + evenSum);
        System.out.println("홀수 합: " + oddSum);
    }
}

📌 실행 예시

시작 숫자 N 입력: 3
끝 숫자 M 입력: 7
짝수 합: 10
홀수 합: 15

🔗 참고 자료

💡 느낀 점

  • switch 문을 사용하면 if-else 문보다 가독성이 좋아짐.
  • while 문을 활용하면 특정 조건을 만족할 때까지 반복 작업을 수행할 수 있음.
  • 무한 루프를 방지하기 위해 탈출 조건과 반복 변수 업데이트가 중요함.

✏️ 요약

✔️ switch 문은 값에 따라 실행할 코드 블록을 선택하는 분기문
✔️ while 문은 특정 조건을 만족하는 동안 반복 실행
✔️ 반복문을 사용할 때는 탈출 조건을 명확히 설정해야 함


profile
Here, My Pale Blue.🌏

0개의 댓글