0

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

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

4

1 回答 1

1

问题出在你的fillUp方法上。特别是这一行:

this.gallons = gallons;

应该:

this.gallons += gallons;

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

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

设置gallons10,然后用20而不是添加覆盖它10,然后添加20总共30.

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

于 2012-09-10T06:54:20.527 回答