Archive for November, 2007

582 Strings and Characters Chapter 10 148 } (Windows 2003 server web)

Friday, November 30th, 2007

582 Strings and Characters Chapter 10 148 } // end method main 149 150 } // end class DeckOfCards 151 152 // class to represent a card 153 class Card { 154 private String face; 155 private String suit; 156 157 // constructor to initialize a card 158 public Card( String cardFace, String cardSuit ) 159 { 160 face = cardFace; 161 suit = cardSuit; 162 } 163 164 // return String represenation of Card 165 public String toString() 166 { 167 return face + ” of ” + suit; 168 } 169 170 } // end class Card Fig. 10.21 Card dealing program (part 4 of 4). Class Card (lines 153 170) contains two String instance variables face and suit that are used to store references to the face name and suit name for a specific Card. The constructor for the class receives two Strings that it uses to initialize face and suit. Method toStringis provided to create a Stringconsisting of the faceof the card, the string “of”and the suitof the card. Class DeckOfCards(lines 11 150) consists of an array deckof 52 Cards, an integer currentCard representing the most recently dealt card in the deck array ( 1 if no cards have been dealt yet) and the GUI components used to manipulate the deck of cards. The constructor method of the application instantiates the deck array (line 29) and uses the for structure at lines 33 35 to fill the deckarray with Cards. Note that each Cardis instantiated and initialized with two Strings one from the faces array (Strings “Ace” through “King”) and one from the suitsarray (”Hearts”, “Diamonds”, “Clubs” and “Spades”). The calculation count%13 always results in a value from 0 to 12 (the Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Chapter 10 Strings and Characters 581 95 container.add(

Friday, November 30th, 2007

Chapter 10 Strings and Characters 581 95 container.add( statusLabel ); 96 97 setSize( 275, 120 ); // set window size 98 show(); // show window 99 } 100 101 // shuffle deck of cards with one-pass algorithm 102 public void shuffle() 103 { 104 currentCard = -1; 105 106 // for each card, pick another random card and swap them 107 for ( int first = 0; first < deck.length; first++ ) { 108 int second = ( int ) ( Math.random() * 52 ); 109 Card temp = deck[ first ]; 110 deck[ first ] = deck[ second ]; 111 deck[ second ] = temp; 112 } 113 114 dealButton.setEnabled( true ); 115 } 116 117 // deal one card 118 public Card dealCard() 119 { 120 if ( ++currentCard < deck.length ) 121 return deck[ currentCard ]; 122 else { 123 dealButton.setEnabled( false ); 124 return null; 125 } 126 } 127 128 // execute application 129 public static void main( String args[] ) 130 { 131 DeckOfCards app = new DeckOfCards(); 132 133 app.addWindowListener( 134 135 // anonymous inner class 136 new WindowAdapter() { 137 138 // terminate application when user closes window 139 public void windowClosing( WindowEvent windowEvent ) 140 { 141 System.exit( 0 ); 142 } 143 144 } // end anonymous inner class 145 146 ); // end call to addWindowListener 147 Fig. 10.21 Card dealing program (part 3 of 4). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

580 Strings and Characters Chapter 10 42 dealButton.addActionListener( (Cool web site)

Thursday, November 29th, 2007

580 Strings and Characters Chapter 10 42 dealButton.addActionListener( 43 44 // anonymous inner class 45 new ActionListener() { 46 47 // deal one card 48 public void actionPerformed( ActionEvent actionEvent ) 49 { 50 Card dealt = dealCard(); 51 52 if ( dealt != null ) { 53 displayField.setText( dealt.toString() ); 54 statusLabel.setText( “Card #: ” + currentCard ); 55 } 56 else { 57 displayField.setText( 58 “NO MORE CARDS TO DEAL” ); 59 statusLabel.setText( 60 “Shuffle cards to continue” ); 61 } 62 } 63 64 } // end anonymous inner class 65 66 ); // end call to addActionListener 67 68 container.add( dealButton ); 69 70 shuffleButton = new JButton( “Shuffle cards” ); 71 shuffleButton.addActionListener( 72 73 // anonymous inner class 74 new ActionListener() { 75 76 // shuffle deck 77 public void actionPerformed( ActionEvent actionEvent ) 78 { 79 displayField.setText( “SHUFFLING …” ); 80 shuffle(); 81 displayField.setText( “DECK IS SHUFFLED” ); 82 } 83 84 } // end anonymous inner class 85 86 ); // end call to addActionListener 87 88 container.add( shuffleButton ); 89 90 displayField = new JTextField( 20 ); 91 displayField.setEditable( false ); 92 container.add( displayField ); 93 94 statusLabel = new JLabel(); Fig. 10.21 Card dealing program (part 2 of 4). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Chapter 10 Strings and (Web host forum) Characters 579 10.21 Card

Wednesday, November 28th, 2007

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

578 Strings and Characters (Multiple domain web hosting) Chapter 10 70 application.addWindowListener(

Tuesday, November 27th, 2007

578 Strings and Characters Chapter 10 70 application.addWindowListener( 71 72 // anonymous inner class 73 new WindowAdapter() { 74 75 // handle event when user closes window 76 public void windowClosing( WindowEvent windowEvent ) 77 { 78 System.exit( 0 ); 79 } 80 81 } // end anonymous inner class 82 83 ); // end call to addWindowListener 84 85 } // end method main 86 87 } // end class TokenTest Fig. 10.20 Tokenizing strings with a StringTokenizerobject (part 3 of 3). The statement at lines 44 45 uses the StringTokenizermethod countTokens to determine the number of tokens in the Stringto be tokenized. The condition in the while structure at lines 47 48 StringTokenizer method hasMoreTokens to determine whether there are more tokens in the String being tokenized. If so, the append method is invoked for the JTextArea outputArea to append the next token to the Stringin the JTextArea. The next token is obtained with a call to StringTokenizermethod nextTokenthat returns a String. The token is output followed by a newline character, so subsequent tokens appear on separate lines. If you would like to change the delimiter String while tokenizing a String, you may do so by specifying a new delimiter string in a nextTokencall as follows: tokens.nextToken( newDelimiterString ); This feature is not demonstrated in the program. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Chapter 10 (Web hosting company) Strings and Characters 577 17 //

Tuesday, November 27th, 2007

Chapter 10 Strings and Characters 577 17 // set up GUI and event handling 18 public TokenTest() 19 { 20 super( “Testing Class StringTokenizer” ); 21 22 Container container = getContentPane(); 23 container.setLayout( new FlowLayout() ); 24 25 promptLabel = 26 new JLabel( “Enter a sentence and press Enter” ); 27 container.add( promptLabel ); 28 29 inputField = new JTextField( 20 ); 30 31 inputField.addActionListener( 32 33 // anonymous inner class 34 new ActionListener() { 35 36 // handle text field event 37 public void actionPerformed( ActionEvent event ) 38 { 39 String stringToTokenize = 40 event.getActionCommand(); 41 StringTokenizer tokens = 42 new StringTokenizer( stringToTokenize ); 43 44 outputArea.setText( “Number of elements: ” + 45 tokens.countTokens() + “nThe tokens are:n” ); 46 47 while ( tokens.hasMoreTokens() ) 48 outputArea.append( tokens.nextToken() + “n” ); 49 } 50 51 } // end anonymous inner class 52 53 ); // end call to addActionListener 54 55 container.add( inputField ); 56 57 outputArea = new JTextArea( 10, 20 ); 58 outputArea.setEditable( false ); 59 container.add( new JScrollPane( outputArea ) ); 60 61 setSize( 275, 260 ); // set the window size 62 show(); // show the window 63 } 64 65 // execute application 66 public static void main( String args[] ) 67 { 68 TokenTest application = new TokenTest(); 69 Fig. 10.20 Tokenizing strings with a StringTokenizerobject (part 2 of 3). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Space web hosting - 576 Strings and Characters Chapter 10 The condition

Monday, November 26th, 2007

576 Strings and Characters Chapter 10 The condition in the if structure on line 23 uses method equals to determine whether the object c1 has the same contents as the object c2 (i.e., the characters inside each object are equal). 10.20 Class StringTokenizer When you read a sentence, your mind breaks the sentence into individual words and punctuation, or tokens, each of which conveys meaning to you. Compilers also perform tokenization. They break up statements into individual pieces like keywords, identifiers, operators and other elements of a programming language. In this section, we study Java s StringTokenizer class (from package java.util), which breaks a string into its component tokens. Tokens are separated from one another by delimiters, typically white- space characters such as blank, tab, newline and carriage return. Other characters can also be used as delimiters to separate tokens. The program in Fig. 10.20 demonstrates class StringTokenizer. The window for class TokenTest displays a JTextField where the user types a sentence to tokenize. Output in this program is displayed in a JTextArea. When the user presses the Enter key in the JTextField, method actionPerformed(lines 37 49) is invoked. Lines 39 40 assign Stringreference stringToTokenize the value in the text in the JTextField returned by calling event.getActionCommand(). Next, lines 41 42 create an instance of class StringTokenizer. This StringTokenizerconstructor takes a Stringargument and creates a StringTokenizer for stringToTokenize that will use the default delimiter string ” ntr” consisting of a space, a newline, a tab and a carriage return for tokenization. There are two other constructors for class StringTokenizer. In the version that takes two String arguments, the second Stringis the delimiter String. In the version that takes three arguments, the second Stringis the delimiter Stringand the third argument (a boolean) determines whether the delimiters are also returned as tokens (only if the argument is true). This is useful if you need to know what the delimiters are. 1 // Fig. 10.20: TokenTest.java 2 // Testing the StringTokenizer class of the java.util package 3 4 // Java core packages 5 import java.util.*; 6 import java.awt.*; 7 import java.awt.event.*; 8 9 // Java extension packages 10 import javax.swing.*; 11 12 public class TokenTest extends JFrame { 13 private JLabel promptLabel; 14 private JTextField inputField; 15 private JTextArea outputArea; 16 Fig. 10.20 Tokenizing strings with a StringTokenizerobject (part 1 of 3). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Chapter 10 Strings and Characters 575 7 8 (Web site hosting)

Sunday, November 25th, 2007

Chapter 10 Strings and Characters 575 7 8 public class OtherCharMethods { 9 10 // test non-static Character methods 11 public static void main( String args[] ) 12 { 13 Character c1, c2; 14 15 c1 = new Character( ‘A’ ); 16 c2 = new Character( ‘a’ ); 17 18 String output = “c1 = ” + c1.charValue() + 19 “nc2 = ” + c2.toString() + 20 “nnhash code for c1 = ” + c1.hashCode() + 21 “nhash code for c2 = ” + c2.hashCode(); 22 23 if ( c1.equals( c2 ) ) 24 output += “nnc1 and c2 are equal”; 25 else 26 output += “nnc1 and c2 are not equal”; 27 28 JOptionPane.showMessageDialog( null, output, 29 “Demonstrating Non-Static Character Methods”, 30 JOptionPane.INFORMATION_MESSAGE ); 31 32 System.exit( 0 ); 33 } 34 35 } // end class OtherCharMethods Fig. 10.19 Non-staticmethods of class Character(part 2 of 2). Lines 15 16 instantiate two Characterobjects and pass character literals to the constructor to initialize those objects. Line 18 uses Character method charValue to return the char value stored in Characterobject c1. Line 19 returns a Stringrepresentation of Characterobject c2using method toString. Lines 20 21perform hashCodecalculations on the Characterobjects c1and c2, respectively. Remember that hash code values are used to store objects in hash tables for fast lookup capabilities (see Chapter 20). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

574 Strings and Characters Chapter 10 89 90 (Abyss web server)

Saturday, November 24th, 2007

574 Strings and Characters Chapter 10 89 90 // execute application 91 public static void main( String args[] ) 92 { 93 StaticCharMethods2 application = new StaticCharMethods2(); 94 95 application.addWindowListener( 96 97 // anonymous inner class 98 new WindowAdapter() { 99 100 // handle event when user closes window 101 public void windowClosing( WindowEvent windowEvent ) 102 { 103 System.exit( 0 ); 104 } 105 106 } // end anonymous inner class 107 108 ); // end call to addWindowListener 109 110 } // end method main 111 112 } // end class StaticCharMethods2 Fig. 10.18 Characterclass staticconversion methods (part 3 of 3). The program in Fig. 10.19 demonstrates the nonstatic methods of class Character the constructor, charValue, toString, hashCodeand equals. 1 // Fig. 10.19: OtherCharMethods.java 2 // Demonstrate the non-static methods of class 3 // Character from the java.lang package. 5 // Java extension packages 6 import javax.swing.*; Fig. 10.19 Non-staticmethods of class Character(part 1 of 2). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Chapter 10 Strings and Characters 573 36 37 (Apache web server)

Friday, November 23rd, 2007

Chapter 10 Strings and Characters 573 36 37 toChar = new JButton( “Convert digit to character” ); 38 39 toChar.addActionListener( 40 41 // anonymous inner class 42 new ActionListener() { 43 44 // handle toChar JButton event 45 public void actionPerformed( ActionEvent actionEvent ) 46 { 47 digit = Integer.parseInt( input.getText() ); 48 radix = 49 Integer.parseInt( radixField.getText() ); 50 JOptionPane.showMessageDialog( null, 51 “Convert digit to character: ” + 52 Character.forDigit( digit, radix ) ); 53 } 54 55 } // end anonymous inner class 56 57 ); // end call to addActionListener 58 59 container.add( toChar ); 60 61 toInt = new JButton( “Convert character to digit” ); 62 63 toInt.addActionListener( 64 65 // anonymous inner class 66 new ActionListener() { 67 68 // handle toInt JButton event 69 public void actionPerformed( ActionEvent actionEvent ) 70 { 71 String s = input.getText(); 72 c = s.charAt( 0 ); 73 radix = 74 Integer.parseInt( radixField.getText() ); 75 JOptionPane.showMessageDialog( null, 76 “Convert character to digit: ” + 77 Character.digit( c, radix ) ); 78 } 79 80 } // end anonymous inner class 81 82 ); // end call to addActionListener 83 84 container.add( toInt ); 85 86 setSize( 275, 150 ); // set the window size 87 show(); // show the window 88 } Fig. 10.18 Characterclass staticconversion methods (part 2 of 3). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01