作业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方法中创建对象,并调用测试用JAVA实现完整代码
时间: 2023-05-27 07:04:11 浏览: 188
MyDate.java
```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 boolean isLeapYear() {
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
return true;
}
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) {
int y = year + years;
int m = month + months;
int d = day + days;
if (m > 12) {
y += m / 12;
m = m % 12;
}
if (d > 31) {
m += d / 31;
d = d % 31;
}
year = y;
month = m;
day = d;
}
public String toString() {
return String.format("%04d-%02d-%02d", year, month, day);
}
}
```
Test04.java
```java
public class Test04 {
public static void main(String[] args) {
MyDate date1 = new MyDate(2020, 2, 29);
System.out.println(date1.isLeapYear()); //true
MyDate date2 = new MyDate(2021, 2, 28);
System.out.println(date2.isLeapYear()); //false
MyDate date3 = new MyDate(2020, 12, 31);
date3.plus(1, 1, 1);
System.out.println(date3); // 2022-02-01
MyDate date4 = new MyDate(2000, 2, 28);
date4.plus(4, 6, 30);
System.out.println(date4); // 2004-09-28
}
}
```
阅读全文