Day.java


Below is the syntax highlighted version of Day.java.


/******************************************************************************
  * Donna Gabai, dgabai, P01
  * Fall 12 practice programming exam 4
  * 
  * Day class for constructing a linked list of events.
  * Dependencies: Event, StdOut
  **********************************************************/

public class Day {
    // instance variable, head of linked list
    private Node first;    // first event of the day
    
    // inner class
    private class Node {
        private Event ev;
        private Node next;       // link to next event of day
    }
    
    // empty constructor
    public Day() {
        first = null;            // no appointments yet
    }
    
    // Add an Event to this Day by order of startTime
    public void addEvent(Event ev) {
        // pack event into a node
        Node newNode = new Node();
        newNode.ev = ev;
        
        // check for empty Day, add the first event
        if (first == null) {
            first = newNode;
            // no possible conflict so return
            return;
        }
        
        // insert in time order
        // check for earliest
        if (ev.getStart() < first.ev.getStart()) {
            newNode.next = first;
            first = newNode;
        }
        
        else {
            Node fit = first;      // where will new Event fit?
            Node t = first;        // traveling thru Event list
            while (t != null && t.ev.getStart() < ev.getStart()) {
                fit = t;     // remember preceding start time
                t = t.next;
            }
            
            // insert new event after fit
            newNode.next = fit.next;
            fit.next = newNode;
        }
    }
    
    // print event list in order, warn about conflicts
    public void show() {
        for (Node t = first; t != null; t = t.next) {
            StdOut.println(t.ev);
            if (t.next != null) {
                if (t.ev.conflict(t.next.ev))
                    StdOut.println("Warning: " + t.ev + " conflicts with "
                                       + t.next.ev);
            }
        }
    }
    
    // test main for Day
    public static void main(String[] args) {
        // set up some events
        Event ev1 = new Event(1000, 1050, "COS126 lecture");
        Event ev2 = new Event(1230, 1320, "COS126 precept");
        Event ev3 = new Event(1200, 1300, "lunch with Bob");
        
        // Add to the same day
        Day tues = new Day();
        tues.addEvent(ev2);
        tues.addEvent(ev1);
        tues.addEvent(ev3);
        
        // Output the events for the day
        tues.show();
    }
}