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

Coin Toss Simulator Write a class named Coin. The Coin class should have the fol

ID: 3826592 • Letter: C

Question

Coin Toss Simulator

Write a class named Coin. The Coin class should have the following member variable:

A string named sideUp. The sideUp 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 (“heads” or “tails”) and initializes the sideUpmember variable accordingly.

A void member function named toss that simulates the tossing of the coin. When the tossmember function is called, it randomly determines the side of the coin that is facing up (“heads” or “tails”) and sets the sideUp member variable accordingly.

A member function named getSideUp that returns the value of the sideUp member variable.

Explanation / Answer

Coin.java

import java.util.Random;

public class Coin {
   //Declaring variable
   private String sideUp;
  
   Random r = null;

   //Zero Argumented Constructor
   public Coin() {
       super();
      
       //Creating the random Class Object
       r = new Random();
      
       //Generate random Number either '1' or '0'
       int random = r.nextInt(2);
      
       /* based on the generated Random number
       * assign "heads" or "tails" to coin face
       */
       if (random == 1)
           this.sideUp = "Heads";
       else if (random == 0)
           this.sideUp = "Tails";
   }

   //This method will randomly generate Head or Tail
   public void toss() {
       r = new Random();
       int random = r.nextInt(2);
       if (random == 1)
           this.sideUp = "Heads";
       else if (random == 0)
           this.sideUp = "Tails";
   }

   //This method displaying the face of the Coin
   public String getSideUp() {
       return sideUp;
   }

}

_______________________

Client.java

public class Client {

   public static void main(String[] args) {
       //Creating an Coin Class object
       Coin c=new Coin();
      
       //displaying the face of the coin
       System.out.println("Coin Face :"+c.getSideUp());
      
       //calling the toss method on the Coin Class
       c.toss();
      
       //displaying the face of the coin
       System.out.println("Coin Face After Toss:"+c.getSideUp());

   }

}

________________________

Output:

Coin Face :Heads
Coin Face After Toss:Tails

_____________Thank You