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

PP 4.1 Write a class called Counter that represents a simple tally counter, whic

ID: 3576882 • Letter: P

Question

PP 4.1 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 called 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

package snippet;

class Counter
{
   private int counter;
   public Counter()
   {
       counter=0;
   }
   public void click()
   {
       counter=counter+1;
   }
  
   public int getCount()
   {
       return counter;
   }
   public void reset()
   {
       counter=0;
   }
}
public class CounterTest {

   public static void main(String[] args) {
       // TODO Auto-generated method stub
       Counter c1=new Counter();
       Counter c2=new Counter();
       System.out.println("For counter_1");
       System.out.println("Increment counter_1 thrice");
       c1.click();
       c1.click();
       c1.click();
       System.out.println("Counter_1 count "+c1.getCount());
       System.out.println("For counter_2");
       System.out.println("Increment counter_2 thrice");
       c2.click();
       c2.click();
       c2.click();
       System.out.println("Counter_2 count "+c2.getCount());
      
       System.out.println("Reset counter 1");
       c1.reset();
       System.out.println("Counter_1 count "+c1.getCount());
      
       System.out.println("Reset counter_2");
       c2.reset();
       System.out.println("Counter_2 count "+c2.getCount());
      

   }

}

=======================================================================

Output:

For counter_1
Increment counter_1 thrice
Counter_1 count 3
For counter_2
Increment counter_2 thrice
Counter_2 count 3
Reset counter 1
Counter_1 count 0
Reset counter_2
Counter_2 count 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