본문 바로가기

Backend/Java

[클래스와 객체] Date is Valid?

MyDate.java

package hiding;

import java.util.Calendar;  // Calendar 불러오기

class MyDate {
	private int day;
	private int month;
	private int year;
	private boolean isValid = true;
	
	public MyDate(int day, int month, int year) {    // 생성자 만들기
		setYear(year);
		setMonth(month);
		setDay(day);
	}
    
    // src -> generate getter and setter
    
	public int getDay() {
		return day;
	}
	public void setDay(int day) {
		switch(month) {
			case 1: case 3: case 5: case 7: case 8: case 10: case 12:  // 1,3,5,7,8,10,12월
				if(day <0 || day >31) {
					isValid = false;
				}
				else {
					this.day = day;
				}
				break;
			case 2:  // 2월
				if((year % 4 ==0 && year % 100 !=0) || (year % 400 ==0)) { // 윤년일때
					if(day <0 || day >29) {
						isValid = false;
					}
					else {
						this.day = day;
					}
				}
				else {
					if(day <0 || day >28) {  
						isValid = false;
					}
					else {
						this.day = day;
					}
				}
				break;
			case 4: case 6: case 9: case 11: // 4,6,9,11월
				if(day <0 || day >30) {
					isValid = false;
				}
				else {
					this.day = day;
				}
				break;
		}
	}
	public int getMonth() {
		return month;
	}
	public void setMonth(int month) {
		if(month <1 || month >12) {
			isValid = false;
		}
		else {
			this.month = month;
		}
	}
	public int getYear() {
		return year;
	}
	public void setYear(int year) {
		if(year > Calendar.getInstance().get(Calendar.YEAR)) {  
			isValid = false;
		}
		else {
			this.year = year;
		}
		
	}
	public String isValid() {
		if(isValid) {
			return "유효한 날짜입니다.";
		}
		else {
			return "유효하지 않은 날짜입니다.";
		}
	}
	
}

MyDateTest.java

package hiding;

import java.util.Calendar;
import java.util.Date;

public class MyDateTest {
	
	public static void main(String[] args) {
		MyDate date1 = new MyDate(30, 2, 2000);  
		System.out.println(date1.isValid());     // 유효하지 않은 날짜입니다.
		MyDate date2 = new MyDate(2, 10, 2006);  
		System.out.println(date2.isValid());     // 유효한 날짜입니다.
        
	}	
}

'Backend > Java' 카테고리의 다른 글

랜덤 숫자 맞히기(do - while문)  (0) 2022.06.29
형변환 연습문제  (0) 2022.06.29
2차원 배열 연습  (0) 2022.06.23
Singleton 패턴  (0) 2022.06.22
반복문으로 별찍기  (0) 2022.06.20