public class Person
{
private String name;
private Date born;
private Date died; //null indicates still alive.
public Person(String initialName, int birthMonth, int birthDay,
int birthYear)
{
name = initialName;
born = new Date(birthMonth, birthDay, birthYear);
died = null;
}
public Person(String initialName, int birthMonth, int birthDay,
int birthYear, int deathMonth, int deathDay,
int deathYear)
{
name = initialName;
born = new Date(birthMonth, birthDay, birthYear);
died = new Date(deathMonth, deathDay, deathYear);
}
public String toString()
{
if (died == null)
return name+", "+born.toString()+" - ";
return name+", "+born.toString()+" - "+died.toString();
}
private class Date implements Comparable
{
private int month, day, year;
Date(int month, int day, int year)
{
this.month = month;
this.day = day;
this.year = year;
}
public int compareTo(Object other)
{
Date otherDate = (Date)other;
if (this.precedes(otherDate)) return -1;
else if (this.equals(otherDate)) return 0;
return 1;
}
public boolean equals(Date otherDate)
{
if (otherDate == null)
return false;
return (day == otherDate.getDay()) &&
(month == otherDate.getMonth()) &&
(year == otherDate.getYear());
}
public int getDay()
{
return day;
}
public int getMonth()
{
return month;
}
public int getYear()
{
return year;
}
/** Method to determine if this Date precedes another one.
* @param otherDate - Date being compared
* @return boolean - TRUE if this Date precedes otherDate
*/
public boolean precedes(Date otherDate)
{
if(otherDate == null)
{
return true;
}
if (year < otherDate.getYear())
{
return true;
}
else if ((year == otherDate.getYear()) && (month < otherDate.getMonth()))
{
return true;
}
else if ((year == otherDate.getYear()) && (month == otherDate.getMonth()) && (day < otherDate.getDay()))
{
return true;
}
else
return false;
}
public String toString()
{
return (month+"/"+day+"/"+year);
}
}
}
the driver (, so far, because i don't know how to test the Comparable interface):
public class Tester
{
public static void main(String[] args)
{
Person p1 = new Person("Bob", 2, 23, 1949, 11, 30, 2003);
Person p2 = new Person("Alice", 3, 12, 1977, 1, 10, 1999);
System.out.println(p1);
System.out.println(p2);
}
}

New Topic/Question
Reply




MultiQuote






|