Java计算MPG错误
我在这个任务中遇到了麻烦,我应该计算某个输入变量的每加仑英里数 任务的规格如下: 我应该计算MPG 这是我的司机:Java计算MPG错误,java,class,math,syntax-error,driver,Java,Class,Math,Syntax Error,Driver,我在这个任务中遇到了麻烦,我应该计算某个输入变量的每加仑英里数 任务的规格如下: 我应该计算MPG 这是我的司机: public class Driver{ public static void main(String[] args){ int odometerReading = 15; P4_Icel_Murad_Car auto = new P4_Icel_Murad_Car(odometerReading); Sys
public class Driver{
public static void main(String[] args){
int odometerReading = 15;
P4_Icel_Murad_Car auto = new P4_Icel_Murad_Car(odometerReading);
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());
}
}
下面是代码的其余部分:
public class P4_Icel_Murad_Car{
private int myStartMiles;
private int myEndMiles;
private double myGallonsUsed;
public int P4_Icel_Murad_Car(int odometerReading){
myStartMiles = odometerReading;
return myStartMiles;
}
public void fillUp(int odometerReading,double gallons){
int Miles = odometerReading - myStartMiles;
double MilesPerGallon = Miles / gallons;
}
public double calculateMPG( int odometerReading, double gallons){
int MPG = (int)(odometerReading/gallons);
return MPG;
}
public void resetMPG(){
myStartMiles = 0;
myEndMiles = 0;
myGallonsUsed = 0;
}
}
当输入15作为起始文件时,结果应为
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
但是我使用的IDE(BlueJ)声称P4_Icel_Murad_Car()不需要任何参数,并且我输入int而不是零。
提前谢谢你的帮助 您的课程名为
P4\u Icel\u Murad\u Car
因此,P4\u Icel\u Murad\u Car
应该是类的构造函数,不能从中返回int
尝试将该方法替换为:
public P4_Icel_Murad_Car(int odometerReading){
myStartMiles = odometerReading;
}
您的代码中有几个错误,下面是带注释的工作版本:
public static class P4_Icel_Murad_Car {
private int myStartMiles;
private int myEndMiles;
private double myGallonsUsed;
public P4_Icel_Murad_Car(final int odometerReading) { // Constructor does not have return type, do not put int before constructor name
this.myStartMiles = odometerReading;
this.myEndMiles = odometerReading; // init end miles with start miles from the start
this.myGallonsUsed = 0;
}
public void fillUp(final int odometerReading, final double gallons) {
this.myEndMiles = odometerReading; // store current odometer
this.myGallonsUsed += gallons; // sum up gas
}
public double calculateMPG() { // calculate mileage, divide by gallons
return (this.myEndMiles - this.myStartMiles) / this.myGallonsUsed;
}
public void resetMPG() { // reset means start from current odometer reading
this.myStartMiles = this.myEndMiles;
this.myGallonsUsed = 0;
}
}