我想记录一个参数的旧值并在旧参数上添加新的参数值,我该如何在 java 中做到这一点?
例如,如何将 auto.fillUp 中的“10”和 auto.fillUp 中的“20”相加?
public class Main {
public static void main(String[] args){
OdometerReading auto = new OdometerReading(15);
auto.fillUp(350, 10);
auto.fillUp(450, 20);
System.out.println("Miles per gallon: " + auto.calculateMPG());
}
}
里程表阅读类:
public class OdometerReading {
public int myStartMiles;
public int myEndMiles;
public double myGallonsUsed;
public int milesInterval;
public double getMyGallonsUsedNew;
public OdometerReading(int assignedCarMiles){
myStartMiles = assignedCarMiles;
System.out.println("New car odometer reading: " + myStartMiles);
}
public void fillUp(int milesDriven, double gallonsUsed){
myEndMiles = milesDriven;
myGallonsUsed = gallonsUsed;
}
public double calculateMPG(){
milesInterval = myEndMiles - myStartMiles;
double mpg = milesInterval / myGallonsUsed;
return mpg;
}
public void reset(){
myStartMiles = myEndMiles;
myGallonsUsed = 0;
}
}
***注意:我是 Java 和编程的初学者,如果这可能是一个“不专业”的问题,我很抱歉。