More exercises creating classes

Exercise - Averaging Objects

In this exercise the task is to fill in the template of a class called Averager.java which contains the sum of a finite number of doubles; it also stores the number of values which have been added and, of these values, the minimum and maximum. Various methods must be defined, one of which calculates the mean based on the total and the number of values. The other methods are:
public class Averager
{
  private double total;
  private int noOfVals;
  private double max;
  private double min;

  public Averager()
  {
    // Code which initialises the private
    // instance variables
  }
  
  public void addValue(double x)
  {
    // Code which adds a value, x, to total and adjusts
    // the other private instance variables accordingly
  }
  
  public double findAverage()
  {
    // Code which calculates and returns the
    // average based on total and noOfVals
  }
  
  public double getTotal()
  {
    // Code which returns total
  }
  
  public int getNoOfVals()
  {
    // Code which returns noOfVals
  }
  
  public double max()
  {
    // Code which returns max
  }
  
  public double min()
  {
    // Code which returns min
  }

  public String toString()
  {
    // Code which converts an Averager object
    // to a string
  }
  
  public boolean equals(Averager a)
  {
    // Code which returns a boolean value depending
    // on whether two Averager objects are equal.
    // You can decide upon your own criteria for
    // this being true!
  }
  
  public void print()
  {
    // Code which prints an Averager object
  }
}

Hints:

 

Exercise - mutable fractions

Instead of add(f) returning a new fraction (this + f), it could simply add f to itself. f1.add(f2) would change f1 by making it into f1+f2, and it would return nothing.

© 2001 Mark Ryan and Alan Sexton