import java.beans.*; /** * The Aveage class finds and keeps track of the average * of an array of Doubles. * * @author Stuart Hansen * @version September 2008 */ public class Average { // We maintain the average in order to have an old // average for the property change event private Double average; // We use pcs to facilitate our property change events private PropertyChangeSupport pcs; // The default constructor public Average() { average = new Double (Double.NaN); pcs = new PropertyChangeSupport (this); } // Return the current Average public Double getAverage() { return average; } // Return the current Average as a String public String toString () { return average.toString(); } // Find the average of an enumeration of Doubles public Double findAverage(Double[] dArr) { Double oldAverage = average; if (dArr.length > 0) { double sum = 0.0; int count = 0; for (Double d : dArr) { sum += d; count++; } average = new Double (sum/count); } else average = Double.NaN; firePropertyChange (new PropertyChangeEvent (this, "average", oldAverage, average)); return average; } // Fire a property change public void firePropertyChange (PropertyChangeEvent e) { pcs.firePropertyChange(e); } // Add a property change listener public void addPropertyChangeListener(PropertyChangeListener pcl) { pcs.addPropertyChangeListener(pcl); } // Delete a property change listener public void removePropertyChangeListener(PropertyChangeListener pcl) { pcs.removePropertyChangeListener(pcl); } }