Question: Modify theCar class by adding two methods: boolean gasHog() evaluates to true if the miles per gallon is lower than 15.0. boolean economyCar() evaluates to
Modify theCar class by adding two methods:
- boolean gasHog()
- evaluates totrue if the miles per gallon is lower than 15.0.
- boolean economyCar()
- evaluates totrue if the miles per gallon is higher than 30.0.
The constructor and thecalculateMPG() method remain unchanged. Each of these new methods should use thecalculateMPG() to get the miles per gallon, not calculate it themselves. Anif-else statement picks the correct boolean return value.
Put user interaction back into themain() method so the user enters values for each car. Themain() 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:
- Saving miles per gallon in an instance variable of the object along withstartMiles, endMiles,andgallons.
- 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.
- Directly calculating miles per gallon inside each of the new methods.
- It is usually best to do a particular calculation in only one 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:
Enter first reading:
10000
Enter second reading:
10400
Enter gallons:
10
Miles per gallon: 40
Economy Car!
class Car { // instance variables double double startMiles; // Stating odometer reading double double endMiles; // Ending odometer reading double 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 ; } int startMile(){ return startMiles; } } Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
