Reputation: 305
public class DecreasingCounter {
private int value; // instance variable that remembers the value of the counter
int valueInitial;
public DecreasingCounter(int valueAtStart) {
this.value = valueAtStart;
}
public void reset(){
this.value = 0;
}
public void setInitial(){
this.valueInitial = 0;
}
}
I need to change the value back to what it was in DecreasingCounter(x);
with setInitial();
using an object variable, but I don't know how.
Upvotes: 0
Views: 1276
Reputation: 137
public class DecreasingCounter { private int value; // instance variable that remembers the value of the counter int valueInitial;
public DecreasingCounter(int valueAtStart) { this.valueInitial = valueAtStart; this.value = valueAtStart; }
public void reset() { this.value = 0; }
public void setInitial() { this.value = this.valueInitial; } }
Upvotes: 0
Reputation: 397
You could add a variable to hold a current number. All your fields will "remember" their value (unlike variables created in the functions/methods). You should store your initial value in valueInitial and then only tamper with the value-variable. Like this:
public class DecreasingCounter {
private int value; // instance variable that remembers the value of the counter
int valueInitial;
public DecreasingCounter(int valueAtStart) {
this.valueInitial = valueAtStart;
this.value=this.valueInitial;
}
public void reset(){
this.value = 0; //Not sure what you want to do here
}
public void countDown(){
this.value--;
}
public void setInitial(){
this.value = this.valueInitial;
}
}
Upvotes: 0
Reputation: 394156
It seems this is what valueInitial
is for :
public DecreasingCounter(int valueAtStart) {
this.valueInitial = valueAtStart;
this.value = valueAtStart;
}
public void setInitial(){
this.value = this.valueInitial;
}
You store the initial value in the constructor (assigning to this.valueInitial
) and restore it in setInitial()
.
You don't want to set this.valueInitial
to 0
, since that will cause you to lose the initial value that was set in the constructor.
Upvotes: 2