package com.study.javastudy.study;

import java.util.Calendar;

public class SwitchExam {
    public static void main(String[] args) {
        //switch, case, default, break

        int value = 2; // 맞는 case가서 그 뒤에 계속 실행한다. 그래서 break를 사용해야 끝난다

        switch (value) {
            case 1:
                System.out.println("1");
//                break;
            case 2:
                System.out.println("2"); // 2
//                break;
            case 3:
                System.out.println("3"); // 3
            default:
                System.out.println("그 외 다른 숫자"); // 그 외 다른 숫자, default는 case선언에 포함되지 않는 것들 출력
        }

        //JDK7 부터 switch 괄호안에 문자열 타입 변수 사용 가능
        String str = "A";
        switch (str) {
            case "A":
                System.out.println("A"); // A출력
                break;
            case "B":
                System.out.println("B");
        }
        // switch문을 다음과 같이도 사용 가능하다
        // 오늘이 몇 월인지 month에 저장
        int month = Calendar.getInstance().get(Calendar.MONTH) + 1;
        String season = "";

        // 아래처럼 case문을 한번에 사용하면 더 짧게 코드를 짤 수 있다
        switch(month) {
            case 1:
            case 2:
            case 12:
                season = "겨울";
                break;
            case 3:
            case 4:
            case 5:
                season = "봄";
                break;
            case 6:
            case 7:
            case 8:
                season = "여름";
                break;
            case 9:
            case 10:
            case 11:
                season = "가을";
                break;
        }
        System.out.println("지금은 " + month + "월이고, " + season + "입니다.");
    }
}

'자바 기초' 카테고리의 다른 글

do while문  (0) 2024.01.26
while 반복문  (0) 2024.01.26
삼항연산자  (0) 2024.01.26
논리 연산자  (0) 2024.01.26
if 조건문  (0) 2024.01.26

+ Recent posts