我试图制作一个MPG计算器,这里有测试用例和预期结果:
我的测试员:
Car auto = new Car(15);
System.out.println("New car odometer reading: ");
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:
Miles per gallon16.875
Miles per gallon16.875
Miles per gallon15.0
Miles per gallon23.647058823529413
我认为问题在于我的填充码,但我真是太愚蠢而且无法弄清楚......
public class Car
{
private int startMiles;
private int endMiles;
private double gallonsUsed;
private int odometerReading;
public Car(int odometerReading) {
startMiles = odometerReading;
endMiles = odometerReading;
}
public void fillUp (int odometerReading, double gallons) {
endMiles = odometerReading;
gallonsUsed = gallonsUsed + gallons;
}
public double calculateMPG() {
double MPG = (endMiles-startMiles)/gallonsUsed;
return MPG;
}
public void resetMPG() {
gallonsUsed = 0;
startMiles = odometerReading;
endMiles = odometerReading;
}
}
请帮忙!我无法解决这个问题。
答案 0 :(得分:1)
您的问题是,您永远不会推进Car
对象的odometerReading
属性(始终为零)。如果不初始化基元int
,it defaults to 0。
快速解决方法是不将您的开始和结束里程设置为odometerReading
属性,而是将startMiles
等同于endMiles
通过此更改,您还可以删除int odometerReading
属性,因为它将不再使用:
public class Car
{
private int startMiles;
private int endMiles;
private double gallonsUsed;
public Car(int odometerReading) {
startMiles = odometerReading;
endMiles = odometerReading;
}
public void fillUp (int odometerReading, double gallons) {
endMiles = odometerReading;
gallonsUsed = gallonsUsed + gallons;
}
public double calculateMPG() {
double MPG = (endMiles-startMiles)/gallonsUsed;
return MPG;
}
public void resetMPG() {
gallonsUsed = 0;
startMiles = endMiles;
}
}
新输出:
新车里程表读数:
每加仑英里数16.875
每加仑英里数16.875
每加仑英里10.0 每加仑英里6.0英里
如果要将输出与预期匹配,请对主类进行以下更改:
public static void main(String[] args) {
Car auto = new Car(15);
System.out.println("New car odometer reading: " + auto.getEndMiles());
auto.fillUp(150,8); //^^Call a getter method
System.out.println("Miles per gallon: " + auto.calculateMPG());
System.out.println("Miles per gallon: " + auto.calculateMPG());
auto.resetMPG(); //^ just add a colon and space
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());
}
为了支持这一点,您必须在Car
课程中添加一个Getter方法,这样您就可以打印当前的里程数:
public int getEndMiles() {
return endMiles;
}
新输出:
新车里程表读数:15
每加仑英里数:16.875
每加仑英里数:16.875
每加仑英里数:10.0
每加仑英里:6.0
答案 1 :(得分:0)
您的odometerReading
字段始终为0. resetMPG()
也会将startMiles
和endMiles
重置为该值。
我想odometerReading
字段应该始终显示应该在填充中设置的总里程数。对方法参数使用相同的名称会增加混淆。