// CoinFlipping.java // Simulates flipping a coin // Exercise 6.30 // Same as old ExerciseD4_30.java // APPLET CODE="CoinFlipping" HEIGHT=400 WIDTH=160 import java.awt.*; import java.awt.event.*; import javax.swing.*; public class CoinFlipping extends JApplet implements ActionListener { // GUI Components JLabel labelHeads, labelTails; JTextField outputH, outputT; JButton b; // counters for heads and tails int heads = 0; int tails = 0; public void init( ) { Container c = getContentPane( ); c.setLayout( new FlowLayout( ) ); labelHeads = new JLabel( "Number of heads" ); outputH = new JTextField( 10 ); outputH.setEditable( false ); c.add( labelHeads ); c.add( outputH ); labelTails = new JLabel( "Number of tails" ); outputT = new JTextField( 10 ); outputT.setEditable( false ); c.add( labelTails ); c.add( outputT ); b = new JButton( "FLIP" ); b.addActionListener( this ); c.add( b ); } public void actionPerformed( ActionEvent e ) { boolean toss = flip( ); if ( toss ) outputH.setText( "" + ++heads ); else outputT.setText( "" + ++tails ); } boolean flip( ) { int rn = ( int ) ( Math.random( ) * 2 ); if ( rn == 0 ) return false; else return true; } }