Question 3-3

Define a Counter class to represent simple counting devices. It should include the following methods.

Counter()
(Constructor method) Constructs a counter holding the initial value 0.

void increment()
Adds one to the value represented by the counter.

int getValue()
Returns the current value represented by the counter.

The following run() method illustrates the use of the Counter type you are to define.
public static void run() {
    Counter a = new Counter();
    Counter b = new Counter();
    a.increment();
    IO.println(a.getValue());     // prints ``1''
    a.increment();
    b.increment();
    IO.println(a.getValue());     // prints ``2''
    IO.println(b.getValue());     // prints ``1''
}
Write your answer below.
public class Counter {

    // : (your code here)

}

Solution

public class Counter {
    private int val;

    public Counter() {
        val = 0;
    }

    public void increment() {
        val++;
    }

    public int getValue() {
        return val;
    }
}

Back to 8:00 Quiz 3