编写一个代表日期的类,其中有代表年月日的三个属性,创建日期对象时要判断参数提供的年月日是否合法,不合法要进行纠正。“年”默认值为2000,月的值在1到12之间,默认值为1;日由一个对应12个月的整型数组给出合法值,特别的,对于2月,通常为28天,但闰月的2月最多29天。闰年是该年值为400的倍数,或者为4的倍数但不为100的倍数。将创建的日期对象输出时,年月日之间用/分隔。
完整代码如下:
package pk1;
public class java {
int year=2000;
int month=1;
int date=28;
public java(int y,int m,int d) {
year=y;
month=m;
date=d;
}
public void pd() {
if(this.month<1||this.month>12)
this.month=1;
int mon[]= {0,31,0,31,30,31,30,31,31,30,31,30,31};
if((this.year%400==0)||((this.year%4==0)&&(this.year%100!=0)))
mon[2]=29;
else
mon[2]=28;
if(this.date<1)
this.date=1;
else if(this.date>mon[this.month])
this.date=mon[this.month];
System.out.println("日期为:"+this.year+"/"+this.month+"/"+this.date);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
java ygrq=new java(2020,13,30);
ygrq.pd();
}
}