Chapter 10 Strings and Characters Outline 10 1

  • Slides: 89
Download presentation
Chapter 10 – Strings and Characters Outline 10. 1 10. 2 10. 3 10.

Chapter 10 – Strings and Characters Outline 10. 1 10. 2 10. 3 10. 4 10. 5 10. 6 10. 7 10. 8 10. 9 10. 10 10. 11 10. 12 10. 13 10. 14 10. 15 Introduction Fundamentals of Characters and Strings String Constructors String Methods length, char. At and get. Chars Comparing Strings String Method hash. Code Locating Characters and Substrings in Strings Extracting Substrings from Strings Concatenating Strings Miscellaneous String Methods Using String Method value. Of String Method intern String. Buffer Class String. Buffer Constructors String. Buffer Methods length, capacity, set. Length and ensure. Capacity 2002 Prentice Hall, Inc. All rights reserved.

Chapter 10 – Strings and Characters 10. 16 10. 17 10. 18 10. 19

Chapter 10 – Strings and Characters 10. 16 10. 17 10. 18 10. 19 10. 20 10. 21 10. 22 String. Buffer Methods char. At, set. Char. At, get. Chars and reverse String. Buffer append Methods String. Buffer Insertion and Deletion Methods Character Class Examples Class String. Tokenizer Card Shuffling and Dealing Simulation (Optional Case Study) Thinking About Objects: Event Handling 2002 Prentice Hall, Inc. All rights reserved.

10. 1 Introduction • String and character processing – – Class java. lang. String.

10. 1 Introduction • String and character processing – – Class java. lang. String. Buffer Class java. lang. Character Class java. util. String. Tokenizer 2002 Prentice Hall, Inc. All rights reserved.

10. 2 Fundamentals of Characters and Strings • Characters – “Building blocks” of Java

10. 2 Fundamentals of Characters and Strings • Characters – “Building blocks” of Java source programs • String – Series of characters treated as single unit – May include letters, digits, etc. – Object of class String 2002 Prentice Hall, Inc. All rights reserved.

10. 3 String Constructors • Class String – Provides nine constructors 2002 Prentice Hall,

10. 3 String Constructors • Class String – Provides nine constructors 2002 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 Outline // Fig. 10. 1: String. Constructors. java // This program demonstrates the String class constructors. // Java extension packages import javax. swing. *; public class String. Constructors { String. Constructo // test String constructors rs. java public static void main( String args[] ) String default constructor { char. Array[] = { 'b', 'i', 'r', 't', 'h', ' ', instantiates empty Linestring 25 'd', 'a', 'y' }; byte. Array[] = { ( byte ) 'n', ( byte ) 'e', Line 26 Constructor copies String ( byte ) 'w', ( byte ) 'y', ( byte ) 'e', ( byte ) 'a', ( byte ) 'r' }; String. Buffer buffer; String s, s 1, s 2, s 3, s 4, s 5, s 6, s 7, output; s = new String( "hello" ); buffer = new String. Buffer( "Welcome to Java // s 1 s 2 s 3 s 4 s 5 s 6 s 7 use String constructors = new String(); = new String( s ); = new String( char. Array, 6, 3 ); = new String( byte. Array, 4, 4 ); = new String( byte. Array ); = new String( buffer ); Line 27 Constructor copies character array Line 28 Constructor copies Programming!" ); character-array subset Line 29 Constructor copies byte Line 30 array Constructor copies byte-array subset Line 31 Constructor copies String. Buffer 2002 Prentice Hall, Inc. All rights reserved.

33 34 35 36 37 38 39 40 41 42 43 44 45 //

33 34 35 36 37 38 39 40 41 42 43 44 45 // append Strings to output = "s 1 = " + s 1 + "ns 2 = " + s 2 + "ns 3 = " + s 3 + "ns 4 = " + s 4 + "ns 5 = " + s 5 + "ns 6 = " + s 6 + "ns 7 = " + s 7; Outline JOption. Pane. show. Message. Dialog( null, output, "Demonstrating String Class Constructors" , JOption. Pane. INFORMATION_MESSAGE ); System. exit( 0 ); } } // end class String. Constructors String. Constructo rs. java 2002 Prentice Hall, Inc. All rights reserved.

10. 4 String Methods length, char. At and get. Chars • Method length –

10. 4 String Methods length, char. At and get. Chars • Method length – Determine String length • Like arrays, Strings always “know” their size • Unlike array, Strings do not have length instance variable • Method char. At – Get character at specific location in String • Method get. Chars – Get entire set of characters in String 2002 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 // // Outline Fig. 10. 2: String. Miscellaneous. java This program demonstrates the length, char. At and get. Chars methods of the String class. Note: Method get. Chars requires a starting point and ending point in the String. The starting point is the actual subscript from which copying starts. The ending point is one past the subscript at which the copying ends. // Java extension packages import javax. swing. *; public class String. Miscellaneous { // test miscellaneous String methods public static void main( String args[] ) { String s 1, output; char. Array[]; s 1 = new String( "hello there" ); char. Array = new char[ 5 ]; String. Miscellane ous. java Line 28 Line 33 // output the string output = "s 1: " + s 1; // test length method output += "n. Length of s 1: " + s 1. length(); // loop through characters in s 1 and display reversed output += "n. The string reversed is: "; for ( int count = s 1. length() - 1; count >= 0; count-- ) output += s 1. char. At( count ) + " "; Determine number of characters in String s 1 Append s 1’s characters in reverse order to String output 2002 Prentice Hall, Inc. All rights reserved.

36 37 38 39 40 41 42 43 44 45 46 47 48 49

36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 // copy characters from string into char array s 1. get. Chars( 0, 5, char. Array, 0 ); output += "n. The character array is: "; Copy (some of) s 1’s Outline characters to char. Array for ( int count = 0; count < char. Array. length; count++ ) output += char. Array[ count ]; JOption. Pane. show. Message. Dialog( null, output, "Demonstrating String Class Constructors" , JOption. Pane. INFORMATION_MESSAGE ); System. exit( 0 ); } } // end class String. Miscellaneous String. Miscellane ous. java Line 37 2002 Prentice Hall, Inc. All rights reserved.

10. 5 Comparing Strings • Comparing String objects – – Method equals. Ignore. Case

10. 5 Comparing Strings • Comparing String objects – – Method equals. Ignore. Case Method compare. To Method region. Matches 2002 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 // // Outline Fig. 10. 3: String. Compare. java This program demonstrates the methods equals, equals. Ignore. Case, compare. To, and region. Matches of the String class. // Java extension packages import javax. swing. JOption. Pane; public class String. Compare { // test String class comparison methods public static void main( String args[] ) { String s 1, s 2, s 3, s 4, output; s 1 s 2 s 3 s 4 = = new new String( String. Compare. ja va "hello" ); "good bye" ); "Happy Birthday" ); "happy birthday" ); Line 25 output = "s 1 = " + s 1 + "ns 2 = " + s 2 + "ns 3 = " + s 3 + "ns 4 = " + s 4 + "nn"; // test for equality if ( s 1. equals( "hello" ) ) output += "s 1 equals "hello"n"; else output += "s 1 does not equal "hello"n" ; Line 31 Method equals tests two objects for equality using lexicographical comparison Equality operator (==) tests // test for equality with == if both references refer to if ( s 1 == "hello" ) same object in memory output += "s 1 equals "hello"n"; else output += "s 1 does not equal "hello"n" ; 2002 Prentice Hall, Inc. All rights reserved.

36 37 38 39 40 41 42 43 44 45 46 47 48 49

36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 // test for equality (ignore case) if ( s 3. equals. Ignore. Case( s 4 ) ) output += "s 3 equals s 4n"; else output += "s 3 does not equal s 4n" ; // test compare. To output += "ns 1. compare. To( "ns 2. compare. To( "ns 1. compare. To( "ns 3. compare. To( "ns 4. compare. To( "nn"; s 2 s 1 s 4 s 3 ) ) ) is is is " " " + + + Test two objects for equality, but ignore case of letters in String s 1. compare. To( s 2. compare. To( s 1. compare. To( s 3. compare. To( s 4. compare. To( s 2 s 1 s 4 s 3 ) ) ) + + + // test region. Matches (case sensitive) if ( s 3. region. Matches( 0, s 4, 0, 5 ) ) output += "First 5 characters of s 3 and s 4 matchn" ; else output += "First 5 characters of s 3 and s 4 do not matchn" ; // test region. Matches (ignore case) if ( s 3. region. Matches( true, 0, s 4, 0, 5 ) ) output += "First 5 characters of s 3 and s 4 match" ; else output += "First 5 characters of s 3 and s 4 do not match" ; Outline Method compare. To compares String objects String. Compare. ja Methodva region. Matches compares portions of two 37 for equality String. Line objects Lines 44 -48 Line 52 and 59 2002 Prentice Hall, Inc. All rights reserved.

65 66 67 68 69 70 71 72 JOption. Pane. show. Message. Dialog( null,

65 66 67 68 69 70 71 72 JOption. Pane. show. Message. Dialog( null, output, "Demonstrating String Class Constructors" , JOption. Pane. INFORMATION_MESSAGE ); Outline System. exit( 0 ); } } // end class String. Compare. ja va 2002 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 Outline // Fig. 10. 4: String. Start. End. java // This program demonstrates the methods starts. With and // ends. With of the String class. // Java extension packages import javax. swing. *; public class String. Start. End { // test String comparison methods for beginning and end // of a String public static void main( String args[] ) { String strings[] = { "started", "starting", "ended", "ending" }; String output = ""; // test method starts. With for ( int count = 0; count < strings. length; count++ ) if ( strings[ count ]. starts. With( "st" ) ) output += """ + strings[ count ] + "" starts with "st"n"; output += "n"; // test method starts. With starting from position // 2 of the string for ( int count = 0; count < strings. length; count++ ) String. Start. End. j ava Line 21 Line 31 Method starts. With determines if String starts with specified characters if ( strings[ count ]. starts. With( "art", 2 ) ) output += """ + strings[ count ] + "" starts with "art" at position 2n" ; output += "n"; 2002 Prentice Hall, Inc. All rights reserved.

36 37 38 39 40 41 42 43 44 45 46 47 48 49

36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 Outline // test method ends. With for ( int count = 0; count < strings. length; count++ ) if ( strings[ count ]. ends. With( "ed" ) ) output += """ + strings[ count ] + "" ends with "ed"n"; JOption. Pane. show. Message. Dialog( null, output, "Demonstrating String Class Comparisons" , JOption. Pane. INFORMATION_MESSAGE ); Method ends. With determines if String ends with specified characters System. exit( 0 ); } } // end class String. Start. End. j ava Line 40 2002 Prentice Hall, Inc. All rights reserved.

10. 6 String Method hash. Code • Hash table – Stores information using calculation

10. 6 String Method hash. Code • Hash table – Stores information using calculation on storable object • Produces hash code – Used to choose location in table at which to store object – Fast lookup 2002 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 // Fig. 10. 5: String. Hash. Code. java // This program demonstrates the method // hash. Code of the String class. Outline // Java extension packages import javax. swing. *; public class String. Hash. Code { // test String hash. Code method public static void main( String args[] ) { String s 1 = "hello", s 2 = "Hello"; String output = "The hash code for "" + s 1 + "" is " + s 1. hash. Code() + "n. The hash code for "" + s 2 + "" is " + s 2. hash. Code(); JOption. Pane. show. Message. Dialog( null, output, "Demonstrating String Method hash. Code", JOption. Pane. INFORMATION_MESSAGE ); String. Hash. Code. j Method hash. Code performs ava hash-code calculation Line 17 and 19 System. exit( 0 ); } } // end class String. Hash. Code 2002 Prentice Hall, Inc. All rights reserved.

10. 7 Locating Characters and Substrings in Strings • Search for characters in String

10. 7 Locating Characters and Substrings in Strings • Search for characters in String – Method index. Of – Method last. Index. Of 2002 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 // Fig. 10. 6: String. Index. Methods. java // This program demonstrates the String // class index methods. Outline // Java extension packages import javax. swing. *; public class String. Index. Methods { // String searching methods public static void main( String args[] ) { String letters = "abcdefghijklm "; // test index. Of to locate a character in a string String output = "'c' is located at index " + letters. index. Of( 'c' ); output += "n'a' is located at index " + letters. index. Of( 'a', 1 ); output += "n'$' is located at index " + letters. index. Of( '$' ); String. Index. Metho ds. java Method index. Of finds first occurrence of Lines character in String 16 -23 Lines 26 -33 // test last. Index. Of to find a character in a string output += "nn. Last 'c' is located at index " + letters. last. Index. Of( 'c' ); output += "n. Last 'a' is located at index " + letters. last. Index. Of( 'a', 25 ); output += "n. Last '$' is located at index " + letters. last. Index. Of( '$' ); Method last. Index. Of finds last occurrence of character in String 2002 Prentice Hall, Inc. All rights reserved.

35 36 37 38 39 40 41 42 43 44 45 46 47 48

35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 // test index. Of to locate a substring in a string output += "nn"def" is located at index " + letters. index. Of( "def" ); Outline output += "n"def" is located at index " + letters. index. Of( "def", 7 ); output += "n"hello" is located at index " + letters. index. Of( "hello" ); // test last. Index. Of to find a substring in a string output += "nn. Last "def" is located at index " + letters. last. Index. Of( "def" ); Methods index. Of and last. Index. Of can also find occurrences of substrings output += "n. Last "def" is located at index " + letters. last. Index. Of( "def", 25 ); output += "n. Last "hello" is located at index " + letters. last. Index. Of( "hello" ); String. Index. Metho ds. java JOption. Pane. show. Message. Dialog( null, output, "Demonstrating String Class "index" Methods" , JOption. Pane. INFORMATION_MESSAGE ); System. exit( 0 ); } } // end class String. Index. Methods 2002 Prentice Hall, Inc. All rights reserved.

Outline String. Index. Metho ds. java 2002 Prentice Hall, Inc. All rights reserved.

Outline String. Index. Metho ds. java 2002 Prentice Hall, Inc. All rights reserved.

10. 8 Extracting Substrings from Strings • Create Strings from other Strings – Extract

10. 8 Extracting Substrings from Strings • Create Strings from other Strings – Extract substrings 2002 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 // Fig. 10. 7: Sub. String. java // This program demonstrates the // String class substring methods. Outline // Java extension packages import javax. swing. *; public class Sub. String { // test String substring methods public static void main( String args[] ) { String letters = "abcdefghijklm "; // test substring methods String output = "Substring from index 20 to end is " + """ + letters. substring( 20 ) + ""n"; output += "Substring from index 0 up to 6 is " + """ + letters. substring( 0, 6 ) + """; JOption. Pane. show. Message. Dialog( null, output, "Demonstrating String Class Substring Methods", JOption. Pane. INFORMATION_MESSAGE ); Beginning at index 20, Sub. String. java extract characters from String letters Line 17 Extract characters from index 0 Line 20 to 6 from String letters System. exit( 0 ); } } // end class Sub. String 2002 Prentice Hall, Inc. All rights reserved.

10. 9 Concatenating Strings • Method concat – Concatenate two String objects 2002 Prentice

10. 9 Concatenating Strings • Method concat – Concatenate two String objects 2002 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // // Fig. This Note does 10. 8: String. Concatenation. java program demonstrates the String class concat method. that the concat method returns a new String object. It not modify the object that invoked the concat method. Outline // Java extension packages import javax. swing. *; public class String. Concatenation { // test String method concat public static void main( String args[] ) { String s 1 = new String( "Happy " ), s 2 = new String( "Birthday" ); String output = "s 1 = " + s 1 + "ns 2 = " + s 2; output += "nn. Result of s 1. concat( s 2 ) = " + s 1. concat( s 2 ); output += "ns 1 after concatenation = " + s 1; JOption. Pane. show. Message. Dialog( null, output, "Demonstrating String Method concat", JOption. Pane. INFORMATION_MESSAGE ); String. Concatenat ion. java Concatenate String Line 20 s 2 to String s 1 Line 22 However, String s 1 is not modified by method concat System. exit( 0 ); } } // end class String. Concatenation 2002 Prentice Hall, Inc. All rights reserved.

10. 10 Miscellaneous String Methods • Miscellaneous String methods – Return modified copies of

10. 10 Miscellaneous String Methods • Miscellaneous String methods – Return modified copies of String – Return character array 2002 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 // Fig. 10. 9: String. Miscellaneous 2. java // This program demonstrates the String methods replace, // to. Lower. Case, to. Upper. Case, trim, to. String and to. Char. Array Outline // Java extension packages import javax. swing. *; public class String. Miscellaneous 2 { // test miscellaneous String methods public static void main( String args[] ) { String s 1 = new String( "hello" ), s 2 = new String( "GOOD BYE" ), s 3 = new String( " spaces " ); String. Miscellane ous 2. java Use method replace to return s 1 copy in which every occurrence of Line 22 with ‘L’ ‘l’ is replaced String output = "s 1 = " + s 1 + "ns 2 = " + s 2 + "ns 3 = " + s 3; Use method to. Upper. Case to Line 26 return s 1 copy in which every character uppercase Lineis 27 // test method replace output += "nn. Replace 'l' with 'L' in s 1: " + s 1. replace( 'l', 'L' ); Use method to. Lower. Case to Line 30 return s 2 copy in which every character uppercase Lineis 33 // test to. Lower. Case and to. Upper. Case output += "nns 1. to. Upper. Case() = " + s 1. to. Upper. Case() + "ns 2. to. Lower. Case() = " + s 2. to. Lower. Case(); // test trim method output += "nns 3 after trim = "" + s 3. trim() + """; // test to. String method output += "nns 1 = " + s 1. to. String(); Use method trim to return s 3 copy in which whitespace is eliminated Use method to. String to return s 1 2002 Prentice Hall, Inc. All rights reserved.

35 36 37 38 39 40 41 42 43 44 45 46 47 48

35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 // test to. Char. Array method char. Array[] = s 1. to. Char. Array(); Use method to. Char. Array to return character array of s 1 Outline output += "nns 1 as a character array = " ; for ( int count = 0; count < char. Array. length; ++count ) output += char. Array[ count ]; JOption. Pane. show. Message. Dialog( null, output, "Demonstrating Miscellaneous String Methods" , JOption. Pane. INFORMATION_MESSAGE ); System. exit( 0 ); } } // end class String. Miscellaneous 2 String. Miscellane ous 2. java Line 36 2002 Prentice Hall, Inc. All rights reserved.

10. 11 Using String Method value. Of • String provides static class methods –

10. 11 Using String Method value. Of • String provides static class methods – Method value. Of • Returns String representation of object, data type, etc. 2002 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 // Fig. 10: String. Value. Of. java // This program demonstrates the String class value. Of methods. Outline // Java extension packages import javax. swing. *; public class String. Value. Of { // test String value. Of methods public static void main( String args[] ) { char. Array[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; boolean b = true; char c = 'Z'; int i = 7; long l = 10000000; float f = 2. 5 f; double d = 33. 333; Object o = "hello"; String output; // assign to an Object reference String. Value. Of. ja va Lines 26 -32 output = "char array = " + String. value. Of( char. Array ) + "npart of char array = " + String. value. Of( char. Array, 3, 3 ) + "nboolean = " + String. value. Of( b ) + "nchar = " + String. value. Of( c ) + static method value. Of of "nint = " + String. value. Of( i ) + class String returns String "nlong = " + String. value. Of( l ) + representation of various types "nfloat = " + String. value. Of( f ) + "ndouble = " + String. value. Of( d ) + "n. Object = " + String. value. Of( o ); 2002 Prentice Hall, Inc. All rights reserved.

34 35 36 37 38 39 40 41 JOption. Pane. show. Message. Dialog( null,

34 35 36 37 38 39 40 41 JOption. Pane. show. Message. Dialog( null, output, "Demonstrating String Class value. Of Methods", JOption. Pane. INFORMATION_MESSAGE ); Outline System. exit( 0 ); } } // end class String. Value. Of. ja va 2002 Prentice Hall, Inc. All rights reserved.

10. 12 String Method intern • String comparisons – Slow operation – Method intern

10. 12 String Method intern • String comparisons – Slow operation – Method intern improves this performance • Returns reference to String • Guarantees reference has same contents as original String 2002 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 Outline // Fig. 10. 11: String. Intern. java // This program demonstrates the intern method // of the String class. // Java extension packages import javax. swing. *; public class String. Intern { // test String method intern public static void main( String args[] ) { String s 1, s 2, s 3, s 4, output; s 1 = new String( "hello" ); s 2 = new String( "hello" ); String. Intern. jav String s 1 and String s 2 a occupy different memory locations // test strings to determine if they are same // String object in memory if ( s 1 == s 2 ) output = "s 1 and s 2 are the same object in memory" ; else output = "s 1 and s 2 are not the same object in memory" ; // test strings for equality of contents if ( s 1. equals( s 2 ) ) output += "ns 1 and s 2 are equal"; else output += "ns 1 and s 2 are not equal" ; // // s 3 s 4 Lines 15 -20 Line 26 Lines 33 -34 String s 1 and String s 2 have same content use String intern method to get a unique copy of "hello" referred to by both s 3 and s 4 = s 1. intern(); = s 2. intern(); Reference returned by s 1. intern() is same as that returned by s 2. intern() 2002 Prentice Hall, Inc. All rights reserved.

36 37 38 39 40 41 42 43 44 45 46 47 48 49

36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 // test strings to determine if they are same // String object in memory if ( s 3 == s 4 ) output += "ns 3 and s 4 are the same object in memory" ; else output += "ns 3 and s 4 are not the same object in memory" ; Outline // determine if s 1 and s 3 refer to same object if ( s 1 == s 3 ) output += "ns 1 and s 3 are the same object in memory" ; else output += "ns 1 and s 3 are not the same object in memory" ; // determine if s 2 and s 4 refer to same object if ( s 2 == s 4 ) output += "ns 2 and s 4 are the same object in memory" ; else output += "ns 2 and s 4 are not the same object in memory" ; String. Intern. jav a // determine if s 1 and s 4 refer to same object if ( s 1 == s 4 ) output += "ns 1 and s 4 are the same object in memory" ; else output += "ns 1 and s 4 are not the same object in memory" ; 2002 Prentice Hall, Inc. All rights reserved.

66 67 68 69 70 71 72 73 JOption. Pane. show. Message. Dialog( null,

66 67 68 69 70 71 72 73 JOption. Pane. show. Message. Dialog( null, output, "Demonstrating String Method intern" , JOption. Pane. INFORMATION_MESSAGE ); Outline System. exit( 0 ); } } // end class String. Intern. jav a 2002 Prentice Hall, Inc. All rights reserved.

10. 13 String. Buffer Class • Class String. Buffer – When String object is

10. 13 String. Buffer Class • Class String. Buffer – When String object is created, its contents cannot change – Used for creating and manipulating dynamic string data • i. e. , modifiable Strings – Can store characters based on capacity • Capacity expands dynamically to handle additional characters – Uses operators + and += for String concatenation 2002 Prentice Hall, Inc. All rights reserved.

10. 14 String. Buffer Constructors • Three String. Buffer constructors – Default creates String.

10. 14 String. Buffer Constructors • Three String. Buffer constructors – Default creates String. Buffer with no characters • Capacity of 16 characters 2002 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 Outline // Fig. 10. 12: String. Buffer. Constructors. java // This program demonstrates the String. Buffer constructors. // Java extension packages import javax. swing. *; public class String. Buffer. Constructors { // test String. Buffer constructors public static void main( String args[] ) { String. Buffer buffer 1, buffer 2, buffer 3; buffer 1 = new String. Buffer(); buffer 2 = new String. Buffer( 10 ); buffer 3 = new String. Buffer( "hello" ); String output "buffer 1 = "nbuffer 2 "nbuffer 3 Default constructor creates empty String. Buffer with capacity of 16 characters Second constructor creates empty String. Buffer with capacity of specified (10) characters String. Buffer. Cons tructors. java Third constructor creates String. Buffer with Line 14 String “hello” and capacity of 16 characters Line 15 = "" + buffer 1. to. String() + """ + = "" + buffer 2. to. String() + """ + = "" + buffer 3. to. String() + """; JOption. Pane. show. Message. Dialog( null, output, "Demonstrating String. Buffer Class Constructors", JOption. Pane. INFORMATION_MESSAGE ); Method to. String returns 16 String Line representation of String. Buffer Lines 19 -21 System. exit( 0 ); } } // end class String. Buffer. Constructors 2002 Prentice Hall, Inc. All rights reserved.

10. 15 String. Buffer Methods length, capacity, set. Length and ensure. Capacity • Method

10. 15 String. Buffer Methods length, capacity, set. Length and ensure. Capacity • Method length – Return String. Buffer length • Method capacity – Return String. Buffer capacity • Method set. Length – Increase or decrease String. Buffer length • Method ensure. Capacity – Set String. Buffer capacity – Guarantee that String. Buffer has minimum capacity 2002 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 // Fig. 10. 13: String. Buffer. Cap. Len. java // This program demonstrates the length and // capacity methods of the String. Buffer class. Outline // Java extension packages import javax. swing. *; public class String. Buffer. Cap. Len { // test String. Buffer methods for capacity and length public static void main( String args[] ) { String. Buffer buffer = new String. Buffer( "Hello, how are you? " ); String output = "buffer = " + buffer. to. String() + "nlength = " + buffer. length() + "ncapacity = " + buffer. capacity(); buffer. ensure. Capacity( 75 ); output += "nn. New capacity = " + buffer. capacity(); buffer. set. Length( 10 ); output += "nn. New length = " + buffer. length() + "nbuf = " + buffer. to. String(); JOption. Pane. show. Message. Dialog( null, output, "String. Buffer length and capacity Methods" , JOption. Pane. INFORMATION_MESSAGE ); Method length returns String. Buffer. Cap. L String. Buffer length en. java Line 17 returns Method capacity String. Buffer capacity Line 18 Use method ensure. Capacity 20 to 75 to set. Line capacity Line 23 Use method set. Length to set length to 10 System. exit( 0 ); } } // end class String. Buffer. Cap. Len 2002 Prentice Hall, Inc. All rights reserved.

Outline Only 10 characters from String. Buffer. Cap. L String. Buffer are printed en.

Outline Only 10 characters from String. Buffer. Cap. L String. Buffer are printed en. java Only 10 characters from String. Buffer are printed 2002 Prentice Hall, Inc. All rights reserved.

10. 16 String. Buffer Methods char. At, set. Char. At, get. Chars and reverse

10. 16 String. Buffer Methods char. At, set. Char. At, get. Chars and reverse • Manipulating String. Buffer characters – Method char. At • Return String. Buffer character at specified index – Method set. Char. At • Set String. Buffer character at specified index – Method get. Chars • Return character array from String. Buffer – Method reverse • Reverse String. Buffer contents 2002 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 Outline // Fig. 10. 14: String. Buffer. Chars. java // The char. At, set. Char. At, get. Chars, and reverse methods // of class String. Buffer. // Java extension packages import javax. swing. *; public class String. Buffer. Chars { // test String. Buffer character methods public static void main( String args[] ) { String. Buffer buffer = new String. Buffer( "hello there" ); String output = "buffer = " + buffer. to. String() + "n. Character at 0: " + buffer. char. At( 0 ) + "n. Character at 4: " + buffer. char. At( 4 ); Lines 16 -17 char. Array[] = new char[ buffer. length() ]; buffer. get. Chars( 0, buffer. length(), char. Array, 0 ); output += "nn. The characters are: "; for ( int count = 0; count < char. Array. length; ++count ) output += char. Array[ count ]; buffer. set. Char. At( 0, 'H' ); buffer. set. Char. At( 6, 'T' ); output += "nnbuf = " + buffer. to. String(); buffer. reverse(); output += "nnbuf = " + buffer. to. String(); Return String. Buffer. Char characters at indices 0 s. java and 4, respectively Return character array Line 20 from String. Buffer Lines 26 -27 Line 30 Replace characters at indices 0 and 6 with ‘H’ and ‘T, ’ respectively Reverse characters in String. Buffer 2002 Prentice Hall, Inc. All rights reserved.

33 34 35 36 37 38 39 40 JOption. Pane. show. Message. Dialog( null,

33 34 35 36 37 38 39 40 JOption. Pane. show. Message. Dialog( null, output, "Demonstrating String. Buffer Character Methods", JOption. Pane. INFORMATION_MESSAGE ); Outline System. exit( 0 ); } } // end class String. Buffer. Char s. java 2002 Prentice Hall, Inc. All rights reserved.

10. 17 String. Buffer append Methods • Method append – Allow data-type values to

10. 17 String. Buffer append Methods • Method append – Allow data-type values to be added to String. Buffer 2002 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 Outline // Fig. 10. 15: String. Buffer. Append. java // This program demonstrates the append // methods of the String. Buffer class. // Java extension packages import javax. swing. *; public class String. Buffer. Append { // test String. Buffer append methods public static void main( String args[] ) { Object o = "hello"; String s = "good bye"; char. Array[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; boolean b = true; char c = 'Z'; int i = 7; long l = 10000000; float f = 2. 5 f; double d = 33. 333; String. Buffer buffer = new String. Buffer(); buffer. append( o ); buffer. append( " " ); String. Buffer. Appe nd. java Line 24 Append String “hello” to String. Buffer 2002 Prentice Hall, Inc. All rights reserved.

27 28 29 30 31 32 33 34 35 36 37 38 39 40

27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 } buffer. append( buffer. append( s ); " " ); char. Array, 0, 3 ); " " ); b ); " " ); c ); " " ); i ); " " ); l ); " " ); f ); " " ); d ); Append “a b c d e f” Append “a b c” Append boolean, char, int, long, float and double JOption. Pane. show. Message. Dialog( null, "buffer = " + buffer. to. String(), "Demonstrating String. Buffer append Methods", JOption. Pane. INFORMATION_MESSAGE ); System. exit( 0 ); } Outline Append String “good bye” String. Buffer. Appe nd. java Line 27 Line 29 Line 31 Lines 33 -43 // end String. Buffer. Append 2002 Prentice Hall, Inc. All rights reserved.

10. 18 String. Buffer Insertion and Deletion Methods • Method insert – Allow data-type

10. 18 String. Buffer Insertion and Deletion Methods • Method insert – Allow data-type values to be inserted into String. Buffer • Methods delete and delete. Char. At – Allow characters to be removed from String. Buffer 2002 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 // Fig. 10. 16: String. Buffer. Insert. java // This program demonstrates the insert and delete // methods of class String. Buffer. Outline // Java extension packages import javax. swing. *; public class String. Buffer. Insert { // test String. Buffer insert methods public static void main( String args[] ) { Object o = "hello"; String s = "good bye"; char. Array[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; boolean b = true; char c = 'K'; int i = 7; long l = 10000000; float f = 2. 5 f; double d = 33. 333; String. Buffer buffer = new String. Buffer(); String. Buffer. Inse rt. java 2002 Prentice Hall, Inc. All rights reserved.

24 25 26 27 28 29 30 31 32 33 34 35 36 37

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 buffer. insert( buffer. insert( 0, 0, 0, 0, 0, o ); " " ); s ); " " ); char. Array ); " " ); b ); " " ); c ); " " ); i ); " " ); l ); " " ); f ); " " ); d ); Outline Use method insert to insert data types in beginning of String. Buffer String output = "buffer after inserts: n" + buffer. to. String(); buffer. delete. Char. At( 10 ); buffer. delete( 2, 6 ); String. Buffer. Inse rt. java Use method delete. Char. At to Linesfrom 24 -40 remove character index 10 in String. Buffer Line 45 // delete 5 in 2. 5 // delete. 333 in 33. 333 output += "nnbuffer after deletes: n" + buffer. to. String(); Line 46 Remove characters from indices 2 through 5 (inclusive) JOption. Pane. show. Message. Dialog( null, output, "Demonstrating String. Bufferer Inserts and Deletes", JOption. Pane. INFORMATION_MESSAGE ); System. exit( 0 ); } } // end class String. Buffer. Insert 2002 Prentice Hall, Inc. All rights reserved.

Outline String. Buffer. Inse rt. java 2002 Prentice Hall, Inc. All rights reserved.

Outline String. Buffer. Inse rt. java 2002 Prentice Hall, Inc. All rights reserved.

10. 19 Character Class Examples • Treat primitive variables as objects – Type wrapper

10. 19 Character Class Examples • Treat primitive variables as objects – Type wrapper classes • Boolean • Character • Double • Float • Byte • Short • Integer • Long – We examine class Character 2002 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 // // Fig. 10. 17: Static. Char. Methods. java Demonstrates the static character testing methods and case conversion methods of class Character from the java. lang package. Outline // Java core packages import java. awt. *; import java. awt. event. *; // Java extension packages import javax. swing. *; public class Static. Char. Methods extends JFrame { private char c; private JLabel prompt. Label; private JText. Field input. Field; private JText. Area output. Area; // set up GUI public Static. Char. Methods() { super( "Static Character Methods" ); Static. Char. Method s. java Container container = get. Content. Pane(); container. set. Layout( new Flow. Layout() ); prompt. Label = new JLabel( "Enter a character and press Enter" ); container. add( prompt. Label ); input. Field = new JText. Field( 5 ); input. Field. add. Action. Listener( 2002 Prentice Hall, Inc. All rights reserved.

35 36 37 38 39 40 41 42 43 44 45 46 47 48

35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 // anonymous inner class new Action. Listener() { Outline // handle text field event public void action. Performed( Action. Event event ) { String s = event. get. Action. Command(); c = s. char. At( 0 ); build. Output (); } } // end anonymous inner class ); // end call to add. Action. Listener container. add( input. Field ); output. Area = new JText. Area( 10, 20 ); container. add( output. Area ); set. Size( 300, 250 ); show(); Static. Char. Method s. java // set the window size // show the window } // display character info in output. Area public void build. Output() { 2002 Prentice Hall, Inc. All rights reserved.

62 63 64 65 66 67 68 69 70 71 72 73 74 75

62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 output. Area. set. Text( "is defined: " + Character. is. Defined( c ) + "nis digit: " + Character. is. Digit( c ) + "nis Java letter: " + Character. is. Java. Identifier. Start( c ) + "nis Java letter or digit: " + Character. is. Java. Identifier. Part( c ) + "nis letter: " + Character. is. Letter( c ) + "nis letter or digit: " + Character. is. Letter. Or. Digit( c ) + "nis lower case: " + Character. is. Lower. Case( "nis upper case: " + Character. is. Upper. Case( "nto upper case: " + Character. to. Upper. Case( "nto lower case: " + Character. to. Lower. Case( } Determine whether c is defined Unicode digit Outline Determine whether c can be used as first character in identifier c c ) ) + + + ); Determine whether c can be Static. Char. Method used as s. java identifier character Determine whether c is a letter Line 63 // execute application public static void main( String args[] ) { Static. Char. Methods application = new Static. Char. Methods(); application. add. Window. Listener( // anonymous inner class new Window. Adapter() { // handle event when user closes window public void window. Closing( Window. Event window. Event ) { System. exit( 0 ); } Determine whether Lineor 66 digit c is letter Linewhether 68 Determine c is uppercase or lowercase Line 69 Line 71 Lines 72 -73 2002 Prentice Hall, Inc. All rights reserved.

93 94 95 96 97 98 99 100 } // end anonymous inner class

93 94 95 96 97 98 99 100 } // end anonymous inner class Outline ); // end call to add. Window. Listener } } // end method main // end class Static. Char. Method s. java 2002 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 // Fig. 10. 18: Static. Char. Methods 2. java // Demonstrates the static character conversion methods // of class Character from the java. lang package. Outline // Java core packages import java. awt. *; import java. awt. event. *; // Java extension packages import javax. swing. *; public class Static. Char. Methods 2 extends JFrame { private char c; private int digit, radix; private JLabel prompt 1, prompt 2; private JText. Field input, radix. Field; private JButton to. Char, to. Int; public Static. Char. Methods 2() { super( "Character Conversion Methods" ); Static. Char. Method s 2. java // set up GUI and event handling Container container = get. Content. Pane(); container. set. Layout( new Flow. Layout() ); prompt 1 = new JLabel( "Enter a digit or character " ); input = new JText. Field( 5 ); container. add( prompt 1 ); container. add( input ); prompt 2 = new JLabel( "Enter a radix " ); radix. Field = new JText. Field( 5 ); container. add( prompt 2 ); container. add( radix. Field ); 2002 Prentice Hall, Inc. All rights reserved.

36 37 38 39 40 41 42 43 44 45 46 47 48 49

36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 to. Char = new JButton( "Convert digit to character" ); Outline to. Char. add. Action. Listener( // anonymous inner class new Action. Listener() { // handle to. Char JButton event public void action. Performed( Action. Event action. Event ) { digit = Integer. parse. Int( input. get. Text() ); radix = Integer. parse. Int( radix. Field. get. Text() ); JOption. Pane. show. Message. Dialog( null, "Convert digit to character: " + Character. for. Digit( digit, radix ) ); } } // end anonymous inner class ); // end call to add. Action. Listener Static. Char. Method s 2. java Use method for. Digit to convert int digit to number-system character specified by int radix container. add( to. Char ); to. Int = new JButton( "Convert character to digit" ); to. Int. add. Action. Listener( // anonymous inner class new Action. Listener() { 2002 Prentice Hall, Inc. All rights reserved.

68 69 70 71 72 73 74 75 76 77 78 79 80 81

68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 Outline // handle to. Int JButton event public void action. Performed( Action. Event action. Event ) { String s = input. get. Text(); c = s. char. At( 0 ); radix = Integer. parse. Int( radix. Field. get. Text() ); JOption. Pane. show. Message. Dialog( null, "Convert character to digit: " + Character. digit( c, radix ) ); } } // end anonymous inner class ); // end call to add. Action. Listener container. add( to. Int ); set. Size( 275, 150 ); show(); // set the window size // show the window Use method digit to convert char c to number-system integer specified by int radix Static. Char. Method s 2. java } Line 77 // execute application public static void main( String args[] ) { Static. Char. Methods 2 application = new Static. Char. Methods 2(); application. add. Window. Listener( // anonymous inner class new Window. Adapter() { 2002 Prentice Hall, Inc. All rights reserved.

100 101 102 103 104 105 106 107 108 109 110 111 112 //

100 101 102 103 104 105 106 107 108 109 110 111 112 // handle event when user closes window public void window. Closing( Window. Event window. Event ) { System. exit( 0 ); } } Outline // end anonymous inner class ); // end call to add. Window. Listener } } // end method main // end class Static. Char. Methods 2 Static. Char. Method s 2. java 2002 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 // Fig. 10. 19: Other. Char. Methods. java // Demonstrate the non-static methods of class // Character from the java. lang package. Outline // Java extension packages import javax. swing. *; public class Other. Char. Methods { // test non-static Character methods public static void main( String args[] ) { Character c 1, c 2; c 1 = new Character( 'A' ); c 2 = new Character( 'a' ); String output = "c 1 = " + c 1. char. Value() + "nc 2 = " + c 2. to. String() + "nnhash code for c 1 = " + c 1. hash. Code() + "nhash code for c 2 = " + c 2. hash. Code(); Other. Char. Methods. Characters non-static methods java char. Value, to. String, hash. Code and equals Lines 18 -23 if ( c 1. equals( c 2 ) ) output += "nnc 1 and c 2 are equal" ; else output += "nnc 1 and c 2 are not equal" ; JOption. Pane. show. Message. Dialog( null, output, "Demonstrating Non-Static Character Methods" , JOption. Pane. INFORMATION_MESSAGE ); System. exit( 0 ); } } // end class Other. Char. Methods 2002 Prentice Hall, Inc. All rights reserved.

Outline Other. Char. Methods. java 2002 Prentice Hall, Inc. All rights reserved.

Outline Other. Char. Methods. java 2002 Prentice Hall, Inc. All rights reserved.

10. 20 Class String. Tokenizer • Tokenizer – Partition String into individual substrings –

10. 20 Class String. Tokenizer • Tokenizer – Partition String into individual substrings – Use delimiter – Java offers java. util. String. Tokenizer 2002 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 Outline // Fig. 10. 20: Token. Test. java // Testing the String. Tokenizer class of the java. util package // Java core packages import java. util. *; import java. awt. event. *; // Java extension packages import javax. swing. *; public class Token. Test extends JFrame { private JLabel prompt. Label; private JText. Field input. Field; private JText. Area output. Area; // set up GUI and event handling public Token. Test() { super( "Testing Class String. Tokenizer" ); Token. Test. java Line 29 Container container = get. Content. Pane(); container. set. Layout( new Flow. Layout() ); prompt. Label = new JLabel( "Enter a sentence and press Enter" ); container. add( prompt. Label ); input. Field = new JText. Field( 20 ); input. Field contains String to be parsed by String. Tokenizer input. Field. add. Action. Listener( // anonymous inner class new Action. Listener() { 2002 Prentice Hall, Inc. All rights reserved.

36 37 38 39 40 41 42 43 44 45 46 47 48 49

36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 Outline // handle text field event Useevent String. Tokenizer to parse public void action. Performed( Action. Event ) String string. Tokenize with { String string. Tokenize = default delimiter “ ntr” event. get. Action. Command(); String. Tokenizer tokens = new String. Tokenizer( string. Tokenize ); Count number of tokens output. Area. set. Text( "Number of elements: " + tokens. count. Tokens() + "n. The tokens are: n" ); while ( tokens. has. More. Tokens() ) output. Area. append( tokens. next. Token() + "n" ); } } // end anonymous inner class ); // end call to add. Action. Listener Token. Test. java Append next token to output. Area, as long as tokens exist Lines 41 -42 container. add( input. Field ); Line 45 output. Area = new JText. Area( 10, 20 ); output. Area. set. Editable( false ); container. add( new JScroll. Pane( output. Area ) ); Lines 47 -48 set. Size( 275, 260 ); show(); // set the window size // show the window } // execute application public static void main( String args[] ) { Token. Test application = new Token. Test(); 2002 Prentice Hall, Inc. All rights reserved.

70 71 72 73 74 75 76 77 78 79 80 81 82 83

70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 application. add. Window. Listener( Outline // anonymous inner class new Window. Adapter() { // handle event when user closes window public void window. Closing( Window. Event window. Event ) { System. exit( 0 ); } } // end anonymous inner class ); // end call to add. Window. Listener } } // end method main // end class Token. Test. java 2002 Prentice Hall, Inc. All rights reserved.

10. 21 Card Shuffling and Dealing Simulation • Develop Deck. Of. Cards application –

10. 21 Card Shuffling and Dealing Simulation • Develop Deck. Of. Cards application – – Create deck of 52 playing cards using Card objects User deals card by clicking “Deal card” button User shuffles deck by clicking “Shuffle cards” button Use random-number generation 2002 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 Outline // Fig. 10. 21: Deck. Of. Cards. java // Card shuffling and dealing program // Java core packages import java. awt. *; import java. awt. event. *; // Java extension packages import javax. swing. *; public class Deck. Of. Cards extends JFrame { private Card deck[]; private int current. Card; private JButton deal. Button, shuffle. Button; private JText. Field display. Field ; private JLabel status. Label; // set up deck of cards and GUI public Deck. Of. Cards() { super( "Card Dealing Program" ); Lines 19 and 29 Deck of 52 Cards String faces[] = { "Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" }; String suits[] = { "Hearts", "Diamonds", "Clubs", "Spades" }; deck = new Card[ 52 ]; current. Card = -1; Deck. Of. Cards. java Line 30 Lines 33 -35 Most recently dealt Cards in deck array (-1 if not Cards have been dealt) // populate deck with Card objects for ( int count = 0; count < deck. length; count++ ) deck[ count ] = new Card( faces[ count % 13 ], suits[ count / 13 ] ); Fill deck array with Cards 2002 Prentice Hall, Inc. All rights reserved.

36 37 38 39 40 41 42 43 44 45 46 47 48 49

36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 Outline // set up GUI and event handling Container container = get. Content. Pane(); container. set. Layout( new Flow. Layout() ); deal. Button = new JButton( "Deal card" ); deal. Button. add. Action. Listener( // anonymous inner class new Action. Listener() { When user presses Deal Card button, method deal. Card gets next card in deck array // deal one card public void action. Performed( Action. Event action. Event ) { Card dealt = deal. Card(); Display Card if ( dealt != null ) { display. Field. set. Text( dealt. to. String() ); status. Label. set. Text( "Card #: " + current. Card ); } else { display. Field. set. Text( "NO MORE CARDS TO DEAL" ); status. Label. set. Text( "Shuffle cards to continue" ); } in JText. Field Deck. Of. Cards. java Line 50 Line 53 } } // end anonymous inner class ); // end call to add. Action. Listener container. add( deal. Button ); 2002 Prentice Hall, Inc. All rights reserved.

70 71 72 73 74 75 76 77 78 79 80 81 82 83

70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 Outline shuffle. Button = new JButton( "Shuffle cards" ); shuffle. Button. add. Action. Listener( // anonymous inner class new Action. Listener() { // shuffle deck public void action. Performed( Action. Event action. Event ) { display. Field. set. Text( "SHUFFLING. . . " ); When user presses Shuffle shuffle(); Cards button, method display. Field. set. Text( "DECK IS SHUFFLED" ); shuffles cards } } // end anonymous inner class ); // end call to add. Action. Listener container. add( shuffle. Button ); display. Field = new JText. Field( 20 ); display. Field. set. Editable( false ); container. add( display. Field ); Deck. Of. Cards. java Line 80 status. Label = new JLabel(); container. add( status. Label ); set. Size( 275, 120 ); show(); // set window size // show window } 2002 Prentice Hall, Inc. All rights reserved.

101 102 103 104 105 106 107 108 109 110 111 112 113 114

101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 Outline // shuffle deck of cards with one-pass algorithm public void shuffle() { current. Card = -1; // for each card, pick another random card and swap them for ( int first = 0; first < deck. length; first++ ) { int second = ( int ) ( Math. random() * 52 ); Card temp = deck[ first ]; deck[ first ] = deck[ second ]; deck[ second ] = temp; } deal. Button. set. Enabled( true ); } // deal one card public Card deal. Card() { if ( ++current. Card < deck. length ) return deck[ current. Card ]; else { deal. Button. set. Enabled( false ); return null; } } Shuffle cards by swapping each Card with randomly selected Card Deck. Of. Cards. java If deck is not empty, a. Lines Card 102 -115 object reference is returned; otherwise, null is returned Lines 118 -126 Lines 114 and 123 Method set. Enabled enables and disables JButton // execute application public static void main( String args[] ) { Deck. Of. Cards app = new Deck. Of. Cards(); app. add. Window. Listener( 2002 Prentice Hall, Inc. All rights reserved.

135 136 137 138 139 140 141 142 143 144 145 146 147 148

135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 Outline // anonymous inner class new Window. Adapter() { // terminate application when user closes window public void window. Closing( Window. Event window. Event ) { System. exit( 0 ); } } // end anonymous inner class ); // end call to add. Window. Listener } } // end method main // end class Deck. Of. Cards // class to represent a card class Card { private String face; private String suit; Deck. Of. Cards. java Store face name and suit for specific Card, respectively Lines 154 -155 // constructor to initialize a card public Card( String card. Face, String card. Suit ) { face = card. Face; suit = card. Suit; } 2002 Prentice Hall, Inc. All rights reserved.

164 165 166 167 168 169 170 // return String represenation of Card public

164 165 166 167 168 169 170 // return String represenation of Card public String to. String() { return face + " of " + suit; } } Outline // end class Card Deck. Of. Cards. java 2002 Prentice Hall, Inc. All rights reserved.

10. 22 (Optional Case Study) Thinking About Objects: Event Handling • How objects interact

10. 22 (Optional Case Study) Thinking About Objects: Event Handling • How objects interact – Sending object sends message to receiving object – We discuss how elevator-system objects interact • Model system behavior 2002 Prentice Hall, Inc. All rights reserved.

10. 22 Thinking About Objects (cont. ) • Event – Message that notifies an

10. 22 Thinking About Objects (cont. ) • Event – Message that notifies an object of an action • Action: Elevator arrives at Floor • Consequence: Elevator sends elevator. Arrived event to Elevator’s Door – i. e. , Door is “notified” that Elevator has arrived • Action: Elevator’s Door opens • Consequence: Door sends door. Opened event to Person – i. e. , Person is “notified” that Door has opened – Preferred naming structure • Noun (“elevator”) preceded by verb (“arrived”) 2002 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 Outline // Elevator. Model. Event. java // Basic event packet holding Location object package com. deitel. jhtp 4. elevator. event; // Deitel packages import com. deitel. jhtp 4. elevator. model. *; public class Elevator. Model. Event { Represents an event in elevator simulation // Location that generated Elevator. Model. Event private Location location; // source of generated Elevator. Model. Event private Object source; // Elevator. Model. Event constructor sets Location public Elevator. Model. Event( Object source, Location location ) { set. Source( source ); set. Location( location ); } // set Elevator. Model. Event Location public void set. Location( Location event. Location ) { location = event. Location; } // get Elevator. Model. Event Location public Location get. Location() { return location; } Location object reference represents location where even was generated Elevator. Model. Eve nt. java Object object reference represents object that generated Line 8 event Line 11 Line 14 2002 Prentice Hall, Inc. All rights reserved.

36 37 38 39 40 41 42 43 44 45 46 47 // set

36 37 38 39 40 41 42 43 44 45 46 47 // set Elevator. Model. Event source private void set. Source( Object event. Source ) { source = event. Source; } Outline // get Elevator. Model. Event source public Object get. Source() { return source; } } Elevator. Model. Eve nt. java 2002 Prentice Hall, Inc. All rights reserved.

10. 22 Thinking About Objects (cont. ) • Every object sends Elevator. Model. Event

10. 22 Thinking About Objects (cont. ) • Every object sends Elevator. Model. Event – This may become confusing • Door sends Elevator. Model. Event to Person upon opening • Elevator sends Elevator. Model. Event to Door upon arrival – Solution: • Create several Elevator. Model. Event subclasses – Each subclass better represents action – e. g. , Bell. Event when Bell rings 2002 Prentice Hall, Inc. All rights reserved.

Fig. 10. 23 Class diagram that models the generalization between Elevator. Model. Event and

Fig. 10. 23 Class diagram that models the generalization between Elevator. Model. Event and its subclasses. 2002 Prentice Hall, Inc. All rights reserved.

Fig. 10. 24 Triggering actions of the Elevator. Model. Event subclass events. 2002 Prentice

Fig. 10. 24 Triggering actions of the Elevator. Model. Event subclass events. 2002 Prentice Hall, Inc. All rights reserved.

10. 22 Thinking About Objects (cont. ) • Event handling – Similar to collaboration

10. 22 Thinking About Objects (cont. ) • Event handling – Similar to collaboration – Object sends message (event) to objects • However, receiving objects must be listening for event – Called event listeners – Listeners must register with sender to receive event 2002 Prentice Hall, Inc. All rights reserved.

10. 22 Thinking About Objects (cont. ) • Modify collaboration diagram of Fig. 7.

10. 22 Thinking About Objects (cont. ) • Modify collaboration diagram of Fig. 7. 20 – Incorporate event handling (Fig. 10. 25) – Three changes • Include notes – Explanatory remarks about UML graphics – Represented as rectangles with corners “folded over” • All interactions happen on first Floor – Eliminates naming ambiguity • Include events – Elevator informs objects of action that has happened • Elevator notifies object of arrival 2002 Prentice Hall, Inc. All rights reserved.

Fig. 10. 25 Modified collaboration diagram for passengers entering and exiting the Elevator on

Fig. 10. 25 Modified collaboration diagram for passengers entering and exiting the Elevator on the first Floor. 2002 Prentice Hall, Inc. All rights reserved.

10. 22 Thinking About Objects (cont. ) • Event listeners – Elevator sends Elevator.

10. 22 Thinking About Objects (cont. ) • Event listeners – Elevator sends Elevator. Move. Event • All event classes (in our simulation) have this structure – Door must implement interface that “listens” for this event – Door implements interface Elevator. Move. Listener • Method elevator. Arrived – Invoked when Elevator arrives • Method elevator. Departed – Invoked when Elevator departs 2002 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // Elevator. Move. Event. java // Indicates on which Floor the Elevator arrived or departed package com. deitel. jhtp 4. elevator. event; Outline // Deitel package import com. deitel. jhtp 4. elevator. model. *; public class Elevator. Move. Event extends Elevator. Model. Event { // Elevator. Move. Event constructor public Elevator. Move. Event( Object source, Location location ) { super( source, location ); } } Elevator. Move. Even t. java 2002 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 // Elevator.

1 2 3 4 5 6 7 8 9 10 11 12 // Elevator. Move. Listener. java // Methods invoked when Elevator has either departed or arrived package com. deitel. jhtp 4. elevator. event; Outline public interface Elevator. Move. Listener { // invoked when Elevator has departed public void elevator. Departed( Elevator. Move. Event move. Event ); // invoked when Elevator has arrived public void elevator. Arrived( Elevator. Move. Event move. Event ); } Elevator. Move. List ener. java 2002 Prentice Hall, Inc. All rights reserved.

10. 22 Thinking About Objects (cont. ) • Class diagram revisited – Modify class

10. 22 Thinking About Objects (cont. ) • Class diagram revisited – Modify class diagram of Fig. 9. 19 to include • Signals (events) – e. g. , Elevator signals arrival to Light • Self associations – e. g. , Light turns itself on and off 2002 Prentice Hall, Inc. All rights reserved.

Fig. 10. 28 Class diagram of our simulator (including event handling). 2002 Prentice Hall,

Fig. 10. 28 Class diagram of our simulator (including event handling). 2002 Prentice Hall, Inc. All rights reserved.