Write a declaration for Car class, using the variable names and method names men
ID: 3881679 • Letter: W
Question
Write a declaration for Car class, using the variable names and method names mentioned below. Leave the bodies of the methods empty.
For programming purposes, we can focus on just a few elements of the state:
Is the engine on?
How much fuel remains in the car's tank?
Instance methods for cars:
startEngine: Stores true into engineIsOn.
stopEngine: Stores false into engineIsOn.
drive: Reduces fuelRemaining by an amount calculated by dividing the distance traveled by the expected fuel consumption.
addFuel: Increase fuelRemaining by a specified amount.
Then write statements that perform the following operations on car.
a. starts car's engine
b. Drive car for 120 miles
c. Add 9.2 gallons to car's tank
d. Stop car's engine
Explanation / Answer
class Car{ private static final double MILE_AGE = 40; boolean engineOn; double fuel; public void startEngine(){ engineOn = true; } public void stopEngine(){ engineOn = false; } public void drive(double dist){ fuel = fuel - dist/MILE_AGE; } public void addFuel(double add){ this.fuel += add; } public String toString(){ return "Car : "+engineOn+" "+fuel; } } public class Main{ public static void main(String[] args) { Car c = new Car(); c.startEngine(); c.drive(120); c.addFuel(9.2); c.stopEngine(); } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.