这个java程序的输出有点不正常?

这个java程序的输出有点不正常?,java,Java,Java代码: public class Car { //variables int myStartMiles; int myEndMiles; double myGallonsUsed; int odometerReading; double gallons; //constructors public Car(int odometerReading) { this.myStartMiles = odomete

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

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

问题在于您的
填充方法。具体而言,这一行:

this.gallons = gallons;
应该是:

this.gallons += gallons;
由于您是赋值而不是添加,因此第三种情况下的输出是错误的,因为:

auto.fillUp(350, 10);
auto.fillUp(450, 20);
加仑设置为
10
,然后用
20
覆盖它,而不是添加
10
,然后添加
20
,总共
30


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

这不起作用,因为这个。加仑将首先包含
8
然后
10
然后
20
所以总计
38
@user1659362@AmitD这是因为
reset
方法重置
myGallonsUsed
而不是
gallons
。我认为这是一个错误,因为
myGallonsUsed
没有在其他任何地方使用。无论哪种方式,您当前处理
加仑的方式肯定是错误的。