[英]How can I record previous parameter values and add to new one?
I want to record old values of a parameter and add new parameter values upon the old ones, how can I do this in java? 我想记录参数的旧值并在旧参数值上添加新参数值,我该如何在java中执行此操作?
For example how can I add up the "10" in the auto.fillUp and the "20" in the auto.fillUp? 例如,如何在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());
}
}
OdometerReading Class: 里程表阅读课程:
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;
}
}
***Note: I am a beginner to Java & programming in general I'm sorry if this may be an "un-professional" question. ***注意:我是Java和编程的初学者我很抱歉,如果这可能是一个“非专业”的问题。
Just make the operation in the method, the state gets saved in the object variable and as long as you have a reference to the object you are good. 只需在方法中进行操作,状态就会保存在对象变量中,只要您有对象的引用即可。
public void fillUp(int milesDriven, double gallonsUsed){
myEndMiles += milesDriven;
myGallonsUsed += gallonsUsed;
}
Note the + operator 注意+运算符
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.