这个java程序的输出有点不正常?
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
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
没有在其他任何地方使用。无论哪种方式,您当前处理加仑的方式肯定是错误的。