Java Code:
public class Car {
//variables
int myStartMiles;
int myEndMiles;
double myGallonsUsed;
int odometerReading;
double gallons;
//constructors
public Car(int odometerReading) {
this.myStartMiles = odometerReading;
this.myEndMiles = myStartMiles;
}
//methods
public void fillUp(int odometerReading, double gallons) {
this.myEndMiles = odometerReading;
this.gallons = gallons;
}
public double calculateMPG() {
int a = (this.myEndMiles - this.myStartMiles);
return ((a) / (this.gallons));
}
public void resetMPG() {
myGallonsUsed = 0;
this.myStartMiles = myEndMiles;
}
public static void main(String[] args) {
int startMiles = 15;
Car auto = new Car(startMiles);
System.out.println("New car odometer reading: " + startMiles);
auto.fillUp(150, 8);
System.out.println("Miles per gallon: " + auto.calculateMPG());
System.out.println("Miles per gallon: " + auto.calculateMPG());
auto.resetMPG();
auto.fillUp(350, 10);
auto.fillUp(450, 20);
System.out.println("Miles per gallon: " + auto.calculateMPG());
auto.resetMPG();
auto.fillUp(603, 25.5);
System.out.println("Miles per gallon: " + auto.calculateMPG());
}
}
I’m trying to get this to work, but I can’t get the desired output.
The desired results are:
New car odometer reading: 15
Miles per gallon: 16.875
Miles per gallon: 16.875
Miles per gallon: 10.0
Miles per gallon: 6.0
I’m getting:
New car odometer reading: 15
Miles per gallon: 16.875
Miles per gallon: 16.875
Miles per gallon: 15.0
Miles per gallon: 6.0
Could you tell me what is wrong with the code? I am trying to manually run it by hand on paper.
The problem is in your
fillUpmethod. Specifically this line:Should be:
Since you are assigning instead of adding, the output is wrong in the third case because:
Sets
gallonsto10and then overwrites it with20instead of adding10, and then adding20for a total of30.EDIT: You will also need
gallons = 0;in yourresetMPGmethod. Currently you setmyGallonsUsed = 0, but that variable is otherwise unused, so I don’t know why you are doing this.