Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a class called counter that represents a simple tally counter, which might

ID: 3887376 • Letter: W

Question

Write a class called counter that represents a simple tally counter, which might be used to count people as they enter a room. The Counter class should contain a single integer as instance data, representing the count. Write a constructor to initialize the count to zero. Write a method called click that increments the count and another method called getCount that returns the current count. Include a method reset that resets the counter to zero. Finally, create a driver class called CounterTest that creates two Counter objects and tests their methods.

Explanation / Answer

CounterTest.java

public class CounterTest {

public static void main(String[] args) {

Counter c = new Counter();

System.out.println("Initial Value: "+c.getCount());

c.click();

c.click();

System.out.println("After two clicks, value: "+c.getCount() );

c.click();

c.click();

c.click();

System.out.println("After five clicks, value: "+c.getCount() );

c.reset();

System.out.println("After reset, value: "+c.getCount());

}

}

Counter.java

public class Counter {

private int count;

public Counter() {

count = 0;

}

public int getCount() {

return count;

}

public void click() {

count++;

}

public void reset() {

count = 0;

}

}

Output:

Initial Value: 0
After two clicks, value: 2
After five clicks, value: 5
After reset, value: 0

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote