MyDate类只有一个构造方法,3个参数year,month,date 为年月日初始化 在构造方法中检查录入的数据是否准确
year: [1900,2099]
month: [1,12]
date: 取决于year和month
如果录入不正确,抛出Exception异常
public class MyDate implements Cloneable,Comparable<MyDate>{
public int year,month,date;
public MyDate(int year,int month,int date) throws Exception {
if (this.year<1900||this.year>2099){
throw new Exception();
}
if (this.month<1||this.month>12){
throw new Exception();
}
int[] mon={1,3,5,7,8,10,12};
int[] mon1={4,6,9,11};
for (int i=0;i<mon.length;i++)
{
if (this.month==mon[i]&&this.date<=31){
}else {
throw new Exception();
}
}
for (int i=0;i<mon1.length;i++)
{
if (this.month==mon1[i]&&this.date<=3){
}else {
throw new Exception();
}
}
if (this.month==2){
if ((this.year%4==0&&year%100!=0)||(this.year%400==0)){
if (this.date > 29) {
throw new Exception();
} else if (this.date>28) {
throw new Exception();
}
}
}
this.year=year;
this.month=month;
this.date=date;
}
public boolean equals(Object obj){
if (obj instanceof MyDate){
MyDate temp=(MyDate) obj;
return (this.year== temp.year&&
this.month==month&&this.date==date);
}
return false;
}
public String toString(){
return "{"+this.year+"-"+this.month+"-"+this.date+"}";
}
public int hashcode(){
return this.year;
}
public Object clone() {
try {
return new MyDate(year,month,date);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public int compareTo(MyDate o) {
if(this.year>o.year){
return 1;
} else if (this.year<o.year) {
return -1;
}else if (this.month>o.month){
return 1;
}else if(this.month<o.month){
return -1;
} else if (this.date>o.date) {
return 1;
}else if (this.date<o.date){
return -1;
}
return 0;
}
}
public class Test1 {
public static void main(String[] args) {
MyDate d1= null;
MyDate d2= null;
MyDate[] da=new MyDate[3];
try {
d1 = new MyDate(1800,01,07);
d2=new MyDate(1997,01,07);
da[0]=new MyDate(1997,01,07);
da[1]=new MyDate(1997,04,07);
da[2]=new MyDate(1997,04,07);
} catch (Exception e) {
throw new RuntimeException(e);
}
System.out.println(d1==d2);
MyDate d3=(MyDate) d1.clone();
System.out.println(d3);
System.out.println(da[0].compareTo(da[1]));
System.out.println(da[2].compareTo(da[1]));
System.out.println(da[1].compareTo(da[0]));
}
}