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


您能告诉我代码有什么问题吗?我正在尝试手动在纸上手动运行它。

最佳答案

问题出在您的fillUp方法中。具体来说这行:

this.gallons = gallons;


应该:

this.gallons += gallons;


由于您是分配而不是添加,因此在第三种情况下输出是错误的,因为:

auto.fillUp(350, 10);
auto.fillUp(450, 20);


gallons设置为10,然后用20覆盖它,而不是添加10,然后添加20总计为30

编辑:您还将在gallons = 0;方法中需要resetMPG。当前,您设置了myGallonsUsed = 0,但该变量未使用,因此我不知道您为什么这样做。

10-07 17:18