Object-Oriented Programming with Java, part I – Exercise 75

This program implements a series of methods in the calls DecreasingCounter to change the initial value.

My Code

public class DecreasingCounter {
    private int value;  // instance variable that remembers the value of the counter
    private int inValue;

    public DecreasingCounter(int valueAtStart) {
        this.value = valueAtStart;
        this.inValue = valueAtStart;
    }

    public void printValue() {
        // do not touch this!
        System.out.println("value: " + this.value);
    }

    public void decrease() {
        // write here code to decrease counter value by one
        if (this.value > 0){
        this.value--;
        }
    }

    // and here the rest of the methods
    public void reset() {
        this.value = 0;
    }
    
    public void setInitial() {
        this.value = this.inValue;
    }
}

Model Code

public class DecreasingCounter {

    private int value;  // instance variable that remembers the value of the counter

    private int initialValue;

 

    public DecreasingCounter(int valueAtStart) {

        this.value = valueAtStart;

        this.initialValue = valueAtStart;

    }

 

    public void printValue() {

        // do not touch this!

        System.out.println("value: " + this.value);

    }

 

    public void decrease() {

        // write here code to decrease counter value by one

        if (this.value > 0) {

            this.value--;

        }

    }

 

    // and here the rest of the methods

    public void reset() {

        this.value = 0;

    }

 

    public void setInitial() {

        this.value = this.initialValue;

    }

}

Comments

Pretty much the same except for a variable name

Leave a comment