public Date(int theMonth,int theDay,int theYear){
month = checkMonth(theMonth);
year = theYear;
day = checkDay(theDay);
System.out.println("Data object constructor for date"+ toDateString());
}
private int checkMonth(int testMonth){
if (testMonth > 0 && testMonth <= 12)
return testMonth;
else{
System.out.println("Invalid month("+ testMonth +")set to 1");
return 1;
}
}
private int checkDay(int testDay){
int daysPerMonth[] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
if(testDay >0 && testDay <= daysPerMonth[month])
return testDay;
if(month ==2 && testDay ==29 && (year %400 ==0 ||
(year %4 ==0 && year %100 != 0)))
return testDay;
System.out.println("Invalid day ("+ testDay +")set to 1");
return 1;
}
public String toDateString()
{
return month + "/" + day + "/" + year;
}
}
//Employee类中应用Date类
public class Employee {
private String firstName;
private String lastName;
private Date birthDate;
private Date hireDate;
public Employee(String first,String last,Date dateofBirth,
Date dateofHire)
{
firstName = first;
lastName = last;
birthDate = dateofBirth;
hireDate = dateofHire;
}
public String toEmployeeString()
{
return lastName + "," + firstName + " Hired:" + hireDate.toDateString()+
"Birthday:"+birthDate.toDateString();
}
}
//程序入口
import javax.swing.JOptionPane;
public class EmployeeTest {
public static void main(String[] args) {
Date birth = new Date(7,24,1949);
Date hire = new Date(3,12,1988);
Employee employee = new Employee("Bob","Jones",birth,hire);
JOptionPane.showMessageDialog(null,employee.toEmployeeString(),"Testing Class Employee",
JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}