Chapter 10 Strings and (Web host forum) Characters 579 10.21 Card
Chapter 10 Strings and Characters 579 10.21 Card Shuffling and Dealing Simulation In this section, we use random number generation to develop a card shuffling and dealing simulation program. This program can then be used to implement programs that play specific card games. We develop application DeckOfCards (Fig. 10.21), which creates a deck of 52 playing cards using Cardobjects, then enables the user to deal each card by clicking on a Dealcard button. Each card dealt is displayed in a JTextField. The user can also shuffle the deck at any time by clicking on a Shufflecards button. 1 // Fig. 10.21: DeckOfCards.java 2 // Card shuffling and dealing program 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 11 public class DeckOfCards extends JFrame { 12 private Card deck[]; 13 private int currentCard; 14 private JButton dealButton, shuffleButton; 15 private JTextField displayField; 16 private JLabel statusLabel; 17 18 // set up deck of cards and GUI 19 public DeckOfCards() 20 { 21 super( “Card Dealing Program” ); 22 23 String faces[] = { “Ace”, “Deuce”, “Three”, “Four”, 24 “Five”, “Six”, “Seven”, “Eight”, “Nine”, “Ten”, 25 “Jack”, “Queen”, “King” }; 26 String suits[] = 27 { “Hearts”, “Diamonds”, “Clubs”, “Spades” }; 28 29 deck = new Card[ 52 ]; 30 currentCard = -1; 31 32 // populate deck with Card objects 33 for ( int count = 0; count < deck.length; count++ ) 34 deck[ count ] = new Card( faces[ count % 13 ], 35 suits[ count / 13 ] ); 36 37 // set up GUI and event handling 38 Container container = getContentPane(); 39 container.setLayout( new FlowLayout() ); 40 41 dealButton = new JButton( “Deal card” ); Fig. 10.21 Card dealing program (part 1 of 4). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01