Java 代码:
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());
}
}
我试图让它工作,但我无法获得所需的输出。
期望的结果是:
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
我越来越:
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
你能告诉我代码有什么问题吗?我正在尝试在纸上手动手动运行它。