定義一個日期類Date

定義一個日期類Date,有年月日三個屬性,實現給屬性賦值獲取的方法,定義輸出日期的方法,定義判斷該日期是否是閏年的方法:public boolean isLeapYear();定義求該日期是這一年的第幾天的方法:public int getDays()。并調用測試

public class Date {
    private int year;
    private int month;
    private int day;

    public Date(int year, int month, int day) {
        super();
        this.year = year;
        this.month = month;
        this.day = day;
    }

    public Date() {
        super();
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        this.month = month;
    }

    public int getDay() {
        return day;
    }

    public void setDay(int day) {
        this.day = day;
    }

    /**
     * 方法名稱:isLeapYear()
     * 方法的作用:判斷是否是閏年
     * 參數:無
     * 返回值:boolean型,true:是閏年,false:不是閏年  *
     */

    public boolean isLeapYear() {
        if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
            return true;
        }
        return false;
    }

    /**
     * 方法名稱:getDays()
     * 方法作用:獲取該日期是這一年的第多少天
     * @param:無
     * @return int,返回天數
     */
    public int getDays() {
        int days = 0;
        for (int i = 1; i < month; i++) {
            if (i == 4 || i == 6 || i == 9 || i == 11) {
                days += 30;
            } else if (i == 2) {
                days += 28;
                if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
                    days++;
                }
            } else {
                days += 31;
            }
        }
        days += day;
        return days;
    }
}

測試:

public class Date_Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Date D1 = new Date(2016, 8, 1);
        boolean a = D1.isLeapYear();
        int b = D1.getDays();

        System.out.println("是否閏年:" + a);
        System.out.println("今天是第" + b + "天");
    }

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容