Date.java


This is the syntax highlighted version of Date.java from 3.4 Encapsulation of
Introduction to Computer Science by Robert Sedgewick and Kevin Wayne.

/*************************************************************************
 *  Compilation:  javac Date.java
 *  Execution:    java Date
 *
 *  ADT for dates (doesn't deal with leap years).
 *
 *************************************************************************/

public class Date {
    private int[] days = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

    private int month;
    private int day;
    private int year;

    public Date(int m, int d, int y) {
        month = m;
        day   = d;
        year  = y;
        if (m < 1 || m > 12)      throw new RuntimeException("Invalid month");
        if (d < 1 || d > days[m]) throw new RuntimeException("Invalid day");
    }

    // return the next Date
    public Date next() {
        Date d = new Date(month, day, year);
        d.year  = year;
        d.month = month;
        d.day   = day + 1;
        if (d.day > days[month]) {
            d.day = 1;
            d.month = d.month + 1;
        }
        if (d.month > 12) {
            d.month = 1;
            d.year  = d.year + 1;
        }
        return d;
    }


    // is this Date a after b?
    public boolean isAfter(Date b) {
        Date a = this;
        if      (a.year > b.year) return true;
        else if (a.year < b.year) return false;

        if      (a.month > b.month) return true;
        else if (a.month < b.month) return false;

        return (a.day > b.day);
    }

    public String toString() {
        return month + "/" + day + "/" + year;
    }



    // sample client for testing
    public static void main(String[] args) {
        Date today = new Date(12, 25, 2004);
        System.out.println(today);
        for (int i = 0; i < 10; i++) {
           today = today.next();
           System.out.println(today);
        }

        System.out.println(today.isAfter(today.next()));
        System.out.println(today.isAfter(today));
        System.out.println(today.next().isAfter(today));
    }

}


Last updated: Mon Jul 26 16:33:49 EDT 2004 .
Copyright © 2004, Robert Sedgewick and Kevin Wayne.