Java

OOP GUIDE / WORK

 

COIN CLASS SOLUTIONS

 

 

TASK – PART 1 – COIN CLASS

 

Here is my solution:

 

 

public class Coin

{

     public String state;   //"heads" or "tails"

     public int hCount;

     public int tCount;

 

     public Coin()

     {

           if (Math.random() <= 0.50)

           {

                state = "heads";

           }

           else

           {

                state = "tails";

           }

           hCount = 0;

           tCount = 0;

     }

    

     public void toss()

     {

           if (Math.random() <= 0.50)

           {

                state = "heads";

                hCount++;

           }

           else

           {

                state = "tails";

                tCount++;

           }         

     }

    

     public String toString()

     {

           return "Coin is showing " + state + ". (H" + hCount + "T" + tCount + ")";

     }

}

 

 

 

TASK – PART 2 – TESTING YOUR COIN CLASS

 

Here is my solution:

 

 

public class CoinTester

{

     public static void main(String[] args)

     {

           Coin penny = new Coin();

           System.out.println(penny);

          

           penny.toss();

           System.out.println(penny);

 

           penny.toss();

           System.out.println(penny);

 

           penny.toss();

           System.out.println(penny);

     }

}