I have some problems with a coin toss program

9.1k Views Asked by At

I am pretty new to java and using codehs, i need to find the amount and percentage of heads/ tails in a 100 toss program. I've got the 100 flips down but the percentage and printing the amount are beyond me, here is my code and thanks for the help

public class CoinFlips extends ConsoleProgram
{
    public void run()
    {
        for (int i = 0; i < 100; i++)
    {
        if (Randomizer.nextBoolean())
        {
            System.out.println("Heads");
        }
        else
        {
        System.out.println("Tails");
        }
        }
    }
}
4

There are 4 best solutions below

0
On BEST ANSWER

Here is a possible solution:

Add:

int headCount = 0;
int tailsCount = 0;

You can use them by:

        if (Randomizer.nextBoolean())
    {
        System.out.println("Heads");
        headsCount++;
    }
    else
    {
    System.out.println("Tails");
        tailsCount++;
    }

Then write a method to calculate the percentage. Since this looks like a homework assignment, I'll leave that to you.

0
On

public class CoinFlips extends ConsoleProgram {

public void run()
{
 int headsCount = 0;
    for (int i = 0; i < 100; i++)
    {
        if (Randomizer.nextBoolean())
        {
            System.out.println("Heads");
            headsCount++;
        }
        else
        {
            System.out.println("Tails");
        }
    }
    float headsPercentage = headsCount/100f;
    System.out.println("Heads percentage: " + headsPercentage.toString());
}


}

This should work

1
On

Problem:

You will need a counter and a variable for the result.

Solution

int TOTAL =100;
int counter =0;
for (int i = 0; i < TOTAL; i++) {
if (Randomizer.nextBoolean()) {
    System.out.println("Heads");
    counter++;
}else{
    System.out.println("Tails");
}

    double procent = (double)counter/TOTAL*100;
    System.out.println("From "+ TOTAL +" flipped coins " + procent+"% were Heads" );
}
3
On

You need to store how many times there had been Heads and how many times Tails: you need a variable to store the Heads and incremeht the variable every time it turns to HEADS. Then after the loop the number in this variable will be the number of HEADS tosses. Tails is 100-heads. For example:

public class CoinFlips extends ConsoleProgram
{
    public void run()
    {
        int heads = 0;
        for (int i = 0; i < 100; i++)
        {
            if (Randomizer.nextBoolean())
            {
                heads++;
                System.out.println("Heads");
            }
            else
            {
                 System.out.println("Tails");
            }
        }
        System.out.println("Percentage of Heads = " + heads + "%");
        System.out.println("Percentage of Tails = " + (100 - heads) + "%");
    }
}

Since the amount of coint tosses is 100, the amount of the HEADS tosses equals the percentage of HEADS tosses, that is why you can output the actual value of the variable.