Reputation: 3
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");
}
}
}
}
Upvotes: 0
Views: 9415
Reputation: 1754
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.
Upvotes: 0
Reputation: 270
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.
Upvotes: 1
Reputation: 48258
You will need a counter and a variable for the result.
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" );
}
Upvotes: 1
Reputation: 1199
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
Upvotes: 0