I am stuck in this code. I have to print results every 30 tosses for 500 total tosses.
I made the 30 but in the loops.
And also percentages are showing as 0

Help or hints would be much appreciated.

import java.util.Random;// program uses class Random

public class CoinTossing 
{
	public static void main (String [] args)
	{
		Random coinTosses = new Random();
		
		System.out.println("START Coin Toss!");
		
		int frequencyHeads=0;//maintains count of heads rolled
		int frequencyTails=0;//maintains count of tails rolled
		int percentageH;
		int percentageT;
		int totalTosses;
		
		
		for (int toss = 1; toss <= 30; toss++)
		{
			int face = coinTosses.nextInt(2);
			
			if (face == 0)
				++frequencyHeads;
			else
				++frequencyTails;
				
		} 
		totalTosses = frequencyHeads + frequencyTails;
		percentageH = ((totalTosses - frequencyTails)/totalTosses);
		percentageT = ((totalTosses - frequencyHeads)/totalTosses);
		System.out.println("Number of tosses\t\tNumber of Heads\\ % \t\tNumber of Tails\\ %");
		System.out.printf("\t%d\t\t\t\t%d  %d\t\t\t\t%d  %d", frequencyHeads + frequencyTails,frequencyHeads,percentageH, frequencyTails,percentageT);
		}

}

When you divide an int with an int you get an int:
12/100 = 0
12.0/100.0 = 0.12

double percentageH = (1.0*frequencyHeads/totalTosses);
double percentageT = (1.0*frequencyTails/totalTosses);

You multiply by 1.0 which is a double, so
1.0*frequencyHeads is also now double and
1.0*frequencyHeads/totalTosses is also now double

And you store into a double.

Thank you for the reply.
I totally omitted that, it makes sense.

Do you know how i could make the loop print every 30 tosses.
I want it to print the results every 30 tosses for 500 tosses.

Have the System.out.println("Number of tosses\t\tNumber of Heads\\ % \t\tNumber of Tails\\ %"); before the loop.

Loop 500 hundred times. Every 30 times, print the System.out.printf("\t%d\t\t\t\t%d %d\t\t\t\t%d %d", frequencyHeads + frequencyTails,frequencyHeads,percentageH, frequencyTails,percentageT); in the loop

I put the System.out.println("Number of tosses\t\tNumber of Heads\\ % \t\tNumber of Tails\\ %"); before the loop otherwise it would print it every time. I got that.

For the Loop 500 hundred times. Every 30 times, print the
I was trying to use if (toss % 30 == 0) and then the System.out.printf("\t%d\t\t\t\t%d %d\t\t\t\t%d %d", frequencyHeads + frequencyTails,frequencyHeads,percentageH, frequencyTails,percentageT); inside the loop.

But it is not working.
Am i thinking it wrong?

Thanks again for your help.

Never mind, my bad i forgot the curly brackets.
It works perfectly.


Thank you for your help.

This article has been dead for over six months. Start a new discussion instead.