简体   繁体   中英

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?

For example how can I add up the "10" in the auto.fillUp and the "20" in the auto.fillUp?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM