mardi 15 novembre 2016

Assistance with a homework exercise regarding random numbers

Exercise: Write a method called threeHeads that repeatedly flips a coin until the results of the coin toss are three heads in a row. You should use a Random object to make it equally likely that a head or a tail will appear. Each time the coin is flipped, display H for heads or T for tails. When three heads in a row are flipped, the method should print a congratulatory message. Here is a possible output of a call to the method:

T T H T T T H T H T H H H Three heads in a row!

The code I have is:

    static void threeHeads()
    {
        Random rand = new Random();
        int counter = 0;
        while (counter != 3)
        {
            int coin = rand.Next(0, 2);
            if (coin == 0)
            {
            counter++;
            Console.Write("H ");
            }
            else
            {
            Console.Write("T ");
            }
        }
        Console.WriteLine("3 heads in a row!");
    }

This code works but ends when heads is shown three times. For example: T T H T H H T or T H H T T T T T T T H T. If anyone can give me advice on how to end it once heads comes out 3 in a row ( H H H ), I would really appreciate it. I don't want anyone to do this for me, I just need help on how to do this.




Aucun commentaire:

Enregistrer un commentaire