Complete 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:

The complete program is below. Copy it to a file and run it.

Complete Program

Here is the complete program. The calculateMPG() method returns a double value to the caller. Since it returns a value, there must be a return statement within its body that returns a value of the correct type.

In the complete program, the calculateMPG() method uses the instance variables of its object to calculate miles per gallon.


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

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

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

}

class MilesPerGallon
{
  public static void main( String[] args ) 
  {
    Car car = new Car( 32456, 32810, 10.6 );
    System.out.println( "Miles per gallon is " + car.calculateMPG() );
  }
}

QUESTION 10:

  • How many objects are in the system the very instant the program starts running?
  • How many objects are in the system just before the program stops running?