作业2:声明一个日期类MyDate,包含属性:年、月、日,并在MyDate类中声明几个方法: 1、boolean isLeapYear():判断当前日期的是闰年吗? 2、void set(int y, int m, int d):修改年,月,日为新日期 3、void puls(int years, int months, int days):加上years年,months月,days天后的日期 并在测试类Test04的main方法中创建对象,并调用测试
时间: 2023-05-29 21:03:13 浏览: 439
MyDate类的代码如下:
public class MyDate {
private int year;
private int month;
private int day;
public MyDate(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public boolean isLeapYear() {
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
return true;
} else {
return false;
}
}
public void set(int y, int m, int d) {
year = y;
month = m;
day = d;
}
public void plus(int years, int months, int days) {
year += years;
month += months;
day += days;
while (day > getDaysOfMonth(year, month)) {
day -= getDaysOfMonth(year, month);
month++;
if (month > 12) {
year++;
month = 1;
}
}
}
private int getDaysOfMonth(int year, int month) {
switch (month) {
case 2:
if (isLeapYear()) {
return 29;
} else {
return 28;
}
case 4:
case 6:
case 9:
case 11:
return 30;
default:
return 31;
}
}
}
测试类Test04的代码如下:
public class Test04 {
public static void main(String[] args) {
MyDate d1 = new MyDate(2021, 2, 28);
System.out.println(d1.isLeapYear()); // 输出false
d1.set(2021, 3, 1);
System.out.println(d1.isLeapYear()); // 输出false
d1.plus(1, 1, 1);
System.out.println(d1.year + "-" + d1.month + "-" + d1.day); // 输出2022-4-2
MyDate d2 = new MyDate(2000, 2, 29);
System.out.println(d2.isLeapYear()); // 输出true
d2.plus(1, 1, 1);
System.out.println(d2.year + "-" + d2.month + "-" + d2.day); // 输出2001-4-2
}
}
输出结果如下:
false
false
2022-4-2
true
2001-4-2
阅读全文