UkoM
UkoM

Reputation: 305

Setting counter value back to initial in class

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

Answers (3)

parag.rane
parag.rane

Reputation: 137

try 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 = valueAtStart; }
public void reset() { this.value = 0; }
public void setInitial() { this.value = this.valueInitial; } }

In your code you try to assign value 0 to the setIntial() method, so it set to 0, so you loose intial value i.e valueAtStart. instead of this you assign this.valueInitial to the setInitial() method.

Upvotes: 0

Saeldin
Saeldin

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

Eran
Eran

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

Related Questions