0

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.

1 Answers1

2

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

Roger
  • 2,912
  • 2
  • 31
  • 39