Day.java


Below is the syntax highlighted version of Day.java.


/*
 * Name: Jude Nelson
 * Precept: P01B, P07A
 * Login: jcnelson
 * 
 * This is the Day solution
 */
public class Day {
  // Inner linked list Node class, of Events
  private class Node {
    private Event ev;
    private Node next;
  }
  
  // head of our linked list
  private Node first = null;
  
  // make my day (--Clint Eastwood)
  public Day() {
    this.first = null;
  }
  
  // Add an event to the day
  public void addEvent( Event ev ) {
    // Put the event into a node
    Node n = new Node();
    n.ev = ev;
    n.next = null;
    
    if( this.first == null ) {
      // no events yet...
      this.first = n;
    }
    else {
      // Find out where to insert the event node.
      // The event node should be inserted just before the
      // first node we see that has a later start date.
      Node insertAt = null;
      for( Node tmp = this.first; tmp != null; tmp = tmp.next ) {
        if( n.ev.getStart() < tmp.ev.getStart() ) {
          break;
        }
        insertAt = tmp;
      }
      
      if( insertAt == null ) {
        // The given event is earlier than all the events.
        // Make it the new start of the list.
        Node tn = this.first;
        this.first = n;
        n.next = tn;
      }
      else {
        // The given event comes after some other event.
        // Insert it.
        Node tn = insertAt.next;
        insertAt.next = n;
        n.next = tn;
      }
    }
  }
  
  // Print out the day, with conflicts.
  // Only need to check adjacent nodes for conflicts
  public void show() {
    for( Node tmp = this.first; tmp != null; tmp = tmp.next ) {
      StdOut.println(tmp.ev);
      if( tmp.next != null ) {
        if( tmp.ev.conflict( tmp.next.ev ) ) {
          StdOut.println("Warning: " + tmp.ev + " conflicts with " + tmp.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(ev1);
    tues.addEvent(ev2);
    tues.addEvent(ev3);
    // Output the events for the Day
    tues.show();
  }
  
}