본문 바로가기

국비교육/국비교육 복습

Day04_condition2_Test03 : 해당 월의 마지막 날짜 출력 (switch ~ case 조건문)

(Q) 사용자에게 월을 입력받아 해당 월의 마지막 날짜를 구하여 출력하는 프로그램을 구현하세요
- 2월은 28일까지 있다고 가정합니다 (윤년은 고려하지 않습니다)
- 4, 6, 9, 11월은 30일까지 있습니다
-1. 3, 5, 7, 8, 10, 12월은 31일까지 있습니다

 

package day04;

import java.lang.*;

public class Day04_condition2_Test03 {

		public static void main(String[] args) {

			int month = 12;

			switch(month) {
			case 2:
				System.out.println("28");
				break;
			case 4: case 6: case 9: case 11:
				System.out.println("30");
				break;
			case 1: case 3: case 5: case 7: case 8: case 10: case 12:
				System.out.println("31");
				break;
			}

		}

	}

 

1) switch(변수명) {case 숫자 ~} 구문

- 변수의 데이터가 case의 숫자 데이터와 같은 값일 때 해당 단계부터 이하의 모든 case의 {}을 수행

- break; 명령을 통해 동작 범위를 제어할 수 있다

ex) 변수의 데이터가 case의 숫자 데이터와 같을 때 해당 case의 {}부터 break;까지 case의 {}로 수행 범위 제한

 

2) switch 구문 앞에 변수를 선언하여 각 case마다 변수의 값를 선언할 수 있다

package condition2;

public class Test03 {

	public static void main(String[] args) {

		int month = 12;

		int day;
		switch(month) {
		case 2:
			day = 28;
			break;
		case 4: case 6: case 9: case 11:
			day = 30;
			break;
		case 1: case 3: case 5: case 7: case 8: case 10: case 12:
			day = 31;
		break;
		}

		System.out.println(month + "월은 " + day + "일까지 있습니다");

	}

}