我想记录参数的旧值并在旧参数值上添加新参数值,我该如何在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& amp;的初学者编程一般我很抱歉,如果这可能是一个“非专业”的问题。
答案 0 :(得分:2)
只需在方法中进行操作,状态就会保存在对象变量中,只要你有对象的引用就好了。
public void fillUp(int milesDriven, double gallonsUsed){
myEndMiles += milesDriven;
myGallonsUsed += gallonsUsed;
}
注意+运算符