- We enhanced the “Vehicle” class from homework page 108.
- We added “fuelLeft” variable inside the “Vehicle” class.
- We added “drive” method with “distance” parameter.
- We added “getDistanceLeft” method.
- Homework:
- Enhance the “Vehicle” class with the following
- Add “addMoreFuel” method with one parameter “fuel” whose data type is “int”:
- Inside the method, it will add parameter “fuel” into “fuelLeft” variable.
- If “fuelLeft” is more than “fuelCap” the program will do the following
- print “Fuel overflow. Capping fuel tank to “+fuelCap to the shell.
- Set “fuelLeft” to “fuelCap”.
- At the end of the method, print the following 2 pieces of information:
- “Your gas tank is now “+fuelLeft+” gallons”
- “You can drive for “+(fuelLeft*mpg)+” miles.”
- Inside the existing “drive” method, change the code to do the following
- Before reducing “fuelLeft”, calculate the distance the vehicle can cover with the “fuelLeft”.
int distanceItCanGo = fuelLeft * mpg.
- if the “fuelLeft” variable is less than or equal to 0, do the following:
- print to the shell: “Out of gas at “+distanceItCanGo+” miles, add more fuel please.”
- set the “fuelLeft” variable to 0.
- Get input from shell.
- “How many gallons of fuel you want to add? “
- After the user enters some number, call the addMoreFuel method and pass whatever the user enters as the parameter.
- Create a new class April4_HomeworkVehicleAddMoreFuel
- Inside the class create the usual “public static void main(String[] args)” method
- Get input from the shell the following 4 information
- “Enter a new vehicle passenger capacity? “
- “Enter a new vehicle fuelCap? “
- “Enter a new vehicle mpg? “
- “How far you want to drive? “
- After getting these 4 pieces of information, create a new Vehicle, “april4Vehicle”. Use the first 3 input from the shells as parameters of the Vehicle constructor.
- Call april4Vehicle.drive method and pass 4th input as the method parameter.
- Run April4_HomeworkVehicleClass
- For vehicle passenger capacity, enter 4.
- For vehicle fuelCap, enter 10.
- For vehicle mpg, enter 20.
- For how far you want to drive, enter 1000.
- The program now should print to the shell: “Out of gas, fill up fuel, please.”
- The program will get input from the user “How many gallons of fuel you want to add?”. Enter 20.
- The program will now print “Fuel overflow. Capping fuel tank to 10.”
- If the program runs properly, it should do the following to the shell:
Enter a new vehicle passenger capacity? 4
Enter a new vehicle fuelCap? 10
Enter a new vehicle mpg? 20
How far you want to drive? 1000
Out of gas at 200 miles, add more fuel please.
How many gallons of fuel you want to add? 100
Fuel overflow. Capping fuel tank to 10.