Reputation: 17
I am trying to call an accelerate
method on a speed
variable that adds 5 to the speed
variable each time it is called. I'm able to do it once in the constructor:
public int getAccelerate() {
accelerate = (speed + 5);
return accelerate;
}
and display it using
System.out.println(car1.getAccelerate());
but that only works once, which displays 105 if the speed variable is 100.
My question is: how do I update the speed variable each time the accelerate
method is called to reflect the new speed value?
Calling it 5 times gives me the output
105
105
105
105
105
where I am trying to get the output
105
110
115
120
125
by calling the same method 5 times.
Upvotes: 0
Views: 1528
Reputation: 6780
Think about what is happening. Your method takes speed
, adds 5
to it, and puts that value in the variable accelerate
. Then it returns accelerate
. So every time, you change accelerate
based on speed
, but you never change speed
! So for example, if speed
is 100
, the first call will return 100 + 5
, the second call will return 100 + 5
, and so on.
If you want this to work properly, change accelerate each time:
public int getAccelerate()
{
accelerate = (accelerate + 5);
return accelerate;
}
Or you could change speed each time:
public int getAccelerate()
{
speed = (speed + 5);
return speed;
}
Upvotes: 2