用Java编写类 `MyDate` 具有属性年月日,要求一个构造函数初始化属性年月日,提供重置日期、增加日期(考虑闰年闰月)、输出日期等成员函数。
时间: 2024-05-09 17:19:42 浏览: 94
以下是 `MyDate` 类的实现:
```java
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 void resetDate(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public void addDays(int days) {
int[] daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (isLeapYear(year)) {
daysInMonth[1] = 29;
}
while (days > 0) {
int daysInCurrMonth = daysInMonth[month - 1];
if (day + days > daysInCurrMonth) {
days -= (daysInCurrMonth - day + 1);
day = 1;
month++;
if (month > 12) {
month = 1;
year++;
if (isLeapYear(year)) {
daysInMonth[1] = 29;
} else {
daysInMonth[1] = 28;
}
}
} else {
day += days;
days = 0;
}
}
}
public void printDate() {
System.out.println(year + "-" + month + "-" + day);
}
private boolean isLeapYear(int year) {
if (year % 4 == 0) {
if (year % 100 == 0) {
if (year % 400 == 0) {
return true;
} else {
return false;
}
} else {
return true;
}
} else {
return false;
}
}
}
```
使用示例:
```java
public class Main {
public static void main(String[] args) {
MyDate date = new MyDate(2021, 7, 1);
date.printDate(); // Output: 2021-7-1
date.resetDate(2022, 1, 1);
date.printDate(); // Output: 2022-1-1
date.addDays(31);
date.printDate(); // Output: 2022-2-1
date.addDays(365);
date.printDate(); // Output: 2023-2-1
}
}
```
阅读全文