# Question about my coin toss program

• February 8th, 2010, 09:24 AM
CheekySpoon
Question about my coin toss program
I made a coin toss program and it shows me the number of heads and tails that are generated by the program. My question is how do I get the program to show me just the percentage of heads and tails that are generated?

Code :

```import javax.swing.JOptionPane; public class Flip { public static void main(String args[]) {   int heads= 0; int tails= 0; for(int i=0;i<26;i++){   double outcome =Math.random(); if(outcome >= 0.5) heads++; else if (outcome < 0.5) tails++;   }   JOptionPane.showMessageDialog(null, "Heads"+" "+heads); JOptionPane.showMessageDialog(null, "Tails"+" "+tails);   }   }```
• February 8th, 2010, 03:56 PM
Shambolic
Re: Question about my coin toss program
Your question is not very clear. Are you having trouble working out how to calculate the percentage, how to display it, or both? Or do you mean something else?

If there are N trials, and heads of them come up heads, the percentage is
Code :

`double pctHeads = (double)heads*100/N`
The type cast to double is so you can get more precision than just the nearest percentage, if you so wish. No more parentheses are needed, due to the rules of operator precendence, but in case you're not sure, the following is equivalent
Code :

`double pctHeads = (((double)heads)*100)/N`

As for displaying it in a sensible way, you need to check out the Formatter class, which mimicks printf of C:
Formatter (Java 2 Platform SE 5.0)

I've never actually used this before; your post made me realise that I've never worried about formatted output in Java!
• February 8th, 2010, 04:39 PM
CheekySpoon
Re: Question about my coin toss program
You made me realize I was doing something wrong and that combined by just walking away from it for a while helped me figure it out. Thanks!
• February 9th, 2010, 03:14 AM
Shambolic
Re: Question about my coin toss program
It's amazing how walking away from a problem and coming back later can make such a difference!
Just yesterday I spent ages trying to write a simple algorithm (in Mathematica, not Java), but couldn't make it work. I got fed up, went home, and when I went back to the problem last night, solved it in about twenty minutes.