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:

• boolean gasHog()
• evaluates to true if the miles per gallon is lower than 15.0.
• boolean economyCar()
• evaluates to true if the miles per gallon is higher than 30.0.

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`.
• This almost seems logical, but is a poor design. Don't keep a permanent copy of a value that can be easily calculated from data. The reason for this is that it adds complexity to the object, but offers little advantage.
2. Directly calculating miles per gallon inside each of the new methods.
• It is usually best to do a particular calculation in only method, and to use it whenever the calculation is needed. Now if there is a bug in the calculation, or the calculation must be modified, there is only one place to look.

Here is a sample run of the program:

```C:\>java Miles
10000
10400
Enter gallons:
10

Miles per gallon: 40
Economy Car!
```

## 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
00000

Filling Station Visit
00350
gallons to fill tank
10
Miles per gallon: 35
Economy Car!

Filling Station Visit