created 09/05/99; revised 06/13/00, 05/07/03,11/09/2012

Chapter 31 Programming Exercises

Exercise 1

Modify the Car class of the chapter by adding two methods:

The constructor and the calculateMPG() method remain unchanged. Each of these new methods should use the calculateMPG() to get the miles per gallon, not calculate it themselves. An if-else statement picks the correct boolean return value.

Put user interaction back into the main() method method so the user enters values for each car. The main() method uses these additional methods to write a message to the user if the car is a gas hog or an economy car.

You might be tempted to make one of these common design errors:

  1. Saving miles per gallon in an instance variable of the object along with startMiles, endMiles, and gallons.
  2. Directly calculating miles per gallon inside each of the new methods.

Here is a sample run of the program:

C:\>java Miles
Enter first reading:
Enter second reading:
Enter gallons:

Miles per gallon: 40
Economy Car!

Click here to go back to the main menu.

Exercise 2

Change the constructor for the Car class so that it has only one parameter, the first reading of the odometer. The miles per gallon cannot yet be calculated. Now add a method to the class:

void fillUp( int miles, double gallons )

This simulates filling up the tank at a gas station: miles is the current odometer reading and gallons is the number of gallons that filled the tank. Save these values in instance variables. With this information, miles per gallon can be calculated. Write the method so that it updates the instance variables each time it is called (simulating another visit to the pumps). After each call calculateMPG() will calculate the latest miles per gallon.

Write a testing class with a main() that constructs a car and calls fillUp() and calculateMPG() a few times.

C:\>java MilesPerGallon
New car odometer reading:

Filling Station Visit
odometer reading
gallons to fill tank
Miles per gallon: 35
Economy Car!

Filling Station Visit
odometer reading
gallons to fill tank
Miles per gallon:    10
Gas Hog!

Click here to go back to the main menu.

End of the Exercises