Java

OOP GUIDE / WORK

 

COUNTER CLASS SOLUTIONS

 

 

TASK – PART 1 – COUNTER CLASS

 

Here is my solution:

 

public class Counter

{

     public int count;

    

     public Counter()

     {

           count = 0;

     }

 

     public void inc()

     {

           count++;

     }

    

     public void dec()

     {

           count--;

     }

    

     public void reset()

     {

           count=0;

     }

    

     public String toString()

     {

           return "Count = " + count;

     }

    

}

 

 

TASK – PART 2 – TESTING YOUR COUNTER CLASS

 

Here is my solution:

 

public class Question02

{

     public static void main(String[] args)

     {

           //Create a Counter object.

           Counter c1 = new Counter();

          

           //Output the Counter to screen.

           System.out.println(c1);  //calls toString()

          

           //Increment the Counter object.

           c1.inc();

          

           //Output the Counter to screen.

           System.out.println(c1);

          

           //Increment the Counter object twice.

           c1.inc();

           c1.inc();

          

           //Output the Counter to screen.

           System.out.println(c1);

          

           //Decrement the Counter object.

           c1.dec();

          

           //Output the Counter to screen.

           System.out.println(c1);

          

           //Reset the Counter object.

           c1.reset();

          

           //Output the Counter to screen.

           System.out.println(c1);

          

           //Create a for loop that will loop ten times.  Inside the loop, increment the counter.

           for (int i=1; i<=10; i++)  //loops 10 times

           {

                c1.inc();

           }

          

           //After the loop, output the counter to screen.

           System.out.println(c1);

     }

}