定義一個日期類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 + "天");
}
}