javac Date.java Employee.java EmployeeTest.java
java Employee
檔名:Date.java
public class Date
{
private int year;
private int month;
private int day;
public Date ( int theYear, int theMonth, int theDay )
{
year = checkYear ( theYear );
month = checkMonth ( theMonth );
day = checkDay ( theDay );
System.out.printf( "建立日期物件 %s\n" , this );
}
private int checkYear( int testYear)
{
if ( testYear>=1900 && testYear<=2008 )
return testYear;
else
{
System.out.printf("不合法的日子(%d),改為預設值1號", testYear);
return 2008;
}
}
private int checkMonth( int testMonth )
{
if ( testMonth > 0 && testMonth <= 12 )
return testMonth;
else
{
System.out.printf("不合法的日子(%d),改為預設值1號", testMonth );
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.printf( "不合法的日子(%d),改為預設值1號", testDay );
return testDay;
}
public String toString()
{
return String.format( "%d/%d/%d", year, month, day );
}
}
檔名:Employee.java
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 toString()
{
return String.format( "%s, %s Hired: %s Birthday: %s", lastName, firstName, hireDate, birthDate );
}
}
檔名:EmployeeTest.java
public class EmployeeTest
{
public static void main ( String args[] )
{
Date birth = new Date( 1949,07,24 );
Date hire = new Date( 2009,03,12 );
Employee employee = new Employee( "Bob" , "Blue" , birth , hire );
System.out.println( employee );
}
}
留言列表