In: Computer Science
Using the Java programming language: Create and implement a class Car that models a car. A Car is invented to have a gasoline tank that can hold a constant max of 12.5 gallons, and an odometer that is set to 0 for a new car. All cars have an original fuel economy of 23.4 miles per gallon, but the value is not constant.
Provide methods for constructing an instance of a Car (one should be zero parameter, and the other should take one parameter, namely a value for the fuel efficiency). Additional method simulates the car traveling a given number of miles (at the end of traveling that user-specified distance, the odometer is updated and the gas tank level is reduced by an elementary calculation using the miles driven and fuel efficiency), to fill a given number of gallons to the tank, to get the odometer reading, and to get the gas tank level in gallons. (Test case that makes sure the tank isn’t already at capacity)
Please find the code below::
Car.java
package classes4;
public class Car {
private final double gasolineTankCapacity =
12.5;
private double tankFuel;
private double odometer;
private double fuelEfficiency;
Car(){
fuelEfficiency =23.4;
tankFuel = 12.5;
odometer = 0;
}
Car(double effIn){
fuelEfficiency =effIn;
tankFuel = 12.5;
odometer = 0;
}
void carTraveling(double miles){
double fuelUsed = 1/fuelEfficiency
* miles;
tankFuel -= fuelUsed;
System.out.println("Fuel remaining
is : "+tankFuel+" gallons");
odometer +=miles;
}
void fillGas(double gasIn){
if(tankFuel+gasIn <=
gasolineTankCapacity){
tankFuel+=gasIn;
}else{
System.out.println("Gas tank cannot have "+gasIn+" gallons of
gasoline");
}
}
double getOdometer(){
return odometer;
}
public static void main(String[] args) {
Car car = new Car();
System.out.println("New car
odometer reading : "+car.getOdometer());
System.out.println("Travelling to
10 miles");
car.carTraveling(10);
System.out.println("Car odometer
reading : "+car.getOdometer());
System.out.println("Filling 20
gallons of gas");
car.fillGas(20);
System.out.println("Filling .001
gallons of gas");
car.fillGas(.001);
}
}
output: