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

12. CoinTossSimulator Writea class named Coin. The Coin class should have the fo

ID: 3663440 • Letter: 1

Question

12. CoinTossSimulator

Writea class named Coin. The Coin class should have the following membervariable : · A string named side Up. The side Up member variable will hold either ”heads” or” tails” indicating the side of the coin that is facing up. The Coin class should have the following member functions: · A default constructor that randomly determines the side of the coin that is facing up (”head” or ”tails”)and initializes the side Up member variable accordingly. · Avoid member function named toss that simulates the tossing of the coin. When the toss member function is called, it randomly determines the side of the coin that is facing up (”heads” or ”tails”)and sets the side Up member variable accordingly. · A member function named getSideUp that returns the value of the side Up member variable. Write a program that demonstrates the Coin class. The program should creates an instance of the class and display the side that is initially facing up. Then, use loop to toss the coin 20 times. Each time the coin is tossed,display the side that is facing up. The program should keep count of the number of times heads is facing up and the number of times tails is facing up, and display those values after the loop finishes.

Explanation / Answer

class Coin
{
   String sideUp;

   Coin()
   {
       sideUp="head";
   }

   void toss()
   {
       int n=(int) (Math.random()*2);

       if(n==0)
           sideUp="head";
       else
           sideUp="tail";
   }

   String getSideUp()
   {
       return sideUp;
   }

}

class Coin_toss
{
   public static void main(String args[])
   {
       Coin o= new Coin();
       int h=0,t=0;
       String s;
       for(int i=0;i<20;i++)
       {
           o.toss();
           s=o.getSideUp();
           System.out.println(s);
           if(s.equals("head"))
               h++;
           else
               t++;

       }
       System.out.println("Number of times Head tossed "+h);
       System.out.println("Number of times Tail tossed "+t);
   }
}