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

In Java, using the Coin class defined below, design and implement a driver class

ID: 3834129 • Letter: I

Question

In Java, using the Coin class defined below, design and implement a driver class called FlipRace whose main method creates two Coin objects, then continually flips them both to see which coin first comes up heads three flips in a row. Continue flipping the coins until one of the coins wins the race, and consider the possibility that they might tie. Print the results of each turn, and at the end print the winner and total number of flips that were required.

public class Coin
{
private final int HEADS = 0;
private final int TAILS = 1;

private int face;

public Coin()
{
flip();
}

public void flip()
{
face = (int)(Math.random() * 2);
}

public boolean isHeads()
{
return (face == HEADS);
}

public String toString()
{
String faceName;
if (face == HEADS)
faceName = "Head";
else
faceName = "Tails";
return faceName;
}
}

Explanation / Answer

Here is the driver program for flipping 2 coins till one of them wins by 3 consecutive flips for head. Tie condition is also considered. Result will print the winner and the number of flips.

public class FlipRace {

   public static void main(String[] args) {
       String result;
       Coin firstCoin = new Coin();
       Coin secondCoin = new Coin();
       int totalFlipCount = 0;
       int firstCoinHeadCount = 0;
       int secondCoinHeadCount = 0;
       while (firstCoinHeadCount <= 2 && secondCoinHeadCount <= 2 ){
           firstCoin.flip();
           secondCoin.flip();
           firstCoinHeadCount = getHeadCount(firstCoin, firstCoinHeadCount);
           secondCoinHeadCount = getHeadCount(secondCoin, secondCoinHeadCount);
           totalFlipCount++;
          
           System.out.println("C1 is " + firstCoin.toString() + " and C2 is " + secondCoin.toString());
       }
      
       if (firstCoinHeadCount == 3 && secondCoinHeadCount == 3)
           result = "First Coin AND Second Coin";
       else if (firstCoinHeadCount == 3)
           result = "First Coin";
       else
           result = "Second Coin" ;
      
       System.out.println("The Winner is " + result);
       System.out.println("Total number of flips required were : " + totalFlipCount);

   }

   private static int getHeadCount(Coin c1, int headCount) {
       if (c1.isHeads())
           headCount++;
       else
           headCount = 0;
       return headCount;
   }

}

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