Runnable Version of the Program

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Answer:

See below.

Runnable Version of the Program

Here is the full version of the program with the new methods. It would be worth your time to study how things fit together. Notice how the big object (a Fleet) is made up of smaller objects (the Cars) and how the methods of the big object are made up from the methods of the smaller objects.

class Fleet
{
  // data
  private Car town;
  private Car suv;

  // constructor
  Fleet( int start1, int end1, double gal1, 
         int start2, int end2, double gal2 )
  {
    town = new Car( start1, end1, gal1) ;
    suv  = new Car( start2, end2, gal2) ;
  }

  // method
  double calculateMPG()
  {
    double sumMPG; 
    sumMPG = town.calculateMPG() + suv.calculateMPG() ;
    return sumMPG/2.0;
  }

  void fillUp( int townOdo, double townGal, int suvOdo, double suvGal)
  {

    town.fillUp( townOdo, townGal );

    suv .fillUp( suvOdo, suvGal );
  }
}

class Car
{
  // data
  private int startMiles;   // Stating odometer reading
  private int endMiles;     // Ending odometer reading
  private double gallons;   // Gallons of gas used between the readings

  // constructor
  Car(  int first, int last, double gals  )
  {
    startMiles = first ;
    endMiles   = last ;
    gallons    = gals ;
  }

  // methods
  double calculateMPG()
  {
    return (endMiles - startMiles)/gallons ;
  }

  void fillUp(int newOdo, double fillUpGals )
  {
     startMiles  =  endMiles ;
     endMiles    =  newOdo ;
     gallons     =  fillUpGals ;
  }
}

class FleetTester
{
  public static void main ( String[] args)
  {
    Fleet myCars = new Fleet( 1000, 1234, 10, 777, 999, 20 );
    System.out.println("Fleet average MPG= " + myCars.calculateMPG() );

    myCars.fillUp( 1434, 10, 1099, 10 );
    System.out.println("new average MPG= " + myCars.calculateMPG() );
  }
}

QUESTION 15:

Have you about had your fill of this?