// Coin Tossing simulation
// Java How to program, 5/e, Exercise 6.30
Import javax.swing. * ;
Import java.awt. * ;
Import java.awt.event. * ;
Public class cointossing extends JApplet Implements ActionListener {
intTailnumber=0, Headnumber=0;
JLabel tosslable,taillable,headlable;
JButton Tossbutton;
JTextField Tailfield,headfield;
Public voidInit ()
{
Container Container=Getcontentpane ();
Container.setlayout (NewFlowLayout ());
Tossbutton= NewJButton ("Toss");
Container.add (Tossbutton);
Taillable= NewJLabel ("Tail frequency is:");
Container.add (taillable);
Tailfield=NewJTextField (Ten);
Container.add (Tailfield);
Headlable= NewJLabel ("Head frequency is:");
Container.add (headlable);
Headfield=NewJTextField (Ten);
Container.add (Headfield);
Tossbutton.addactionlistener ( This);
}
Public voidactionperformed (ActionEvent event)
{
if (Flip ())
Tailnumber+ +;
Else
Headnumber+ +;
Tailfield.settext (integer.tostring (Tailnumber));
Headfield.settext (integer.tostring (Headnumber));
}
Public BooleanFlip ()
{
return math.random ()<0. 5 ;
}
}