728x90
[문제]
년도와 달을 입력받으면 해당 달의 마지막 날을 구하는 프로그램을 작성한다.
윤달의 조건과 달의 마지막날은 다음과 같다.
* 4의 배수이고 100의 배수가 아니면 윤년
* 4의 배수이고 400의 배수이면 윤년
* 윤년이면 2월은 29, 아니면 28일
* 1, 3, 5, 7, 8, 10, 12 > 31일
* 4, 6, 9, 11 > 30일
[입력예제]
2021 2
[출력예제]
28
[코드]
import java.util.Scanner;
public class LeapYear {
public static void switchTest(int year, int month) {
int lastDay=31;
switch(month) {
case 2:
if(year%4==0 && year%100 !=0 || year%4==0 && year%400==0) { // ||보다 &&가 우선순위가 먼저임
lastDay=29;
}else {
lastDay=28;
}
break;
case 4:
case 6:
case 9:
case 11:
lastDay=30;
}
System.out.println(lastDay);
}
public static void ifTest(int year, int month) {
int lastDay=31;
if(month==2) {
if(year%4==0 && year%100 !=0 || year%4==0 && year%400==0) { // ||보다 &&가 우선순위가 먼저임
lastDay=29;
}else {
lastDay=28;
}
}else if(month==4 || month==6 || month==9 || month==11) {
lastDay = 30;
}
System.out.println(lastDay);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("년/월을 입력하세요 >> ");
int year = sc.nextInt();
int month = sc.nextInt();
ifTest(year, month);
switchTest(year, month);
sc.close();
}
}
[설명]
- Scanner를 이용하여 년/월을 입력받는다.
- ifTest(), switchTest()함수를 이용하여 출력한다.
swich문
- 31일이 마지막 날인 달이 많으므로 lastDay를 31로 초기화 한다.
- 입력받은 달을 switch 조건문으로 생성한다. (month)
- 만약 month가 2일 때, 윤달의 조건에 따라 29일 또는 28일을 lastDay에 넣는다.
- 4, 6, 9, 11월은 30일까지 있으므로 lastDay에 30을 넣는다.
- lastDay를 출력한다.
if문
- 31일이 마지막 날인 달이 많으므로 lastDay를 31로 초기화 한다.
- 입력받은 달(month)이 2월이면, 윤달의 조건에 따라 29일 또는 28일을 lastDay에 넣는다.
- 4, 6, 9, 11월은 30일까지 있으므로 lastDay에 30을 넣는다.
- lastDay를 출력한다.
728x90
반응형
'문제풀이 > JAVA' 카테고리의 다른 글
[JAVA] [프로그래머스] 두 개 뽑아서 더하기 (0) | 2021.03.05 |
---|---|
[JAVA] Caesar Cipher (0) | 2021.03.02 |
[JAVA] 일차원 배열 오름차순 정렬 (0) | 2021.02.17 |
[JAVA] 태어난 계절 (0) | 2021.02.17 |