Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String,...

77
Chapter 10 - Strings and Characters
  • date post

    19-Dec-2015
  • Category

    Documents

  • view

    228
  • download

    0

Transcript of Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String,...

Page 1: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

Chapter 10 - Strings and Characters

Page 2: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

10.1Introduction

• In this chapter– Discuss class String, StringBuffer, and Character

(java.lang)

– Discuss class StringTokenizer (java.util)

– Techniques used here appropriate for making word processors, text editors, page layout software

Page 3: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

10.2Fundamentals of Characters and Strings

• Characters– Character constant - integer represented as a character in

single quotes (Unicode character set)• 'z' is integer value of z

• Strings– Group of characters treated as a single unit

– May include letters, digits, special characters (+,- *...)

– Strings are objects of class String

Page 4: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

10.2Fundamentals of Characters and Strings

• Strings (continued)– String literal (string constants or anonymous String

objects)• Sequence of characters written in double quotes• "John Q. Doe" or "111222333"• Java treats all anonymous String objects with same contents

as one object with many references

– Assigning strings• May assign in declaration

String color = "blue";• color is a String reference

Page 5: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

10.3String Constructors

• Constructors for class String– s1 = new String()

• s1 is an empty string

– s2 = new String( anotherString )• s2 is a copy of anotherString

– s3 = new String( charArray )• s3 contains all the characters in charArray

– s4 = new String( charArray, offset, numElements )

• s4 contains numElements characters from charArray, starting at location offset

– s5 = new String( byteArray, offset, numElements)

• As above, but with a byteArray

Page 6: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

10.3String Constructors

• Constructors for class String– s6 = new String( byteArray )

• s6 contains copy of entire byteArray

• StringBuffer– Dynamically resizable, modifiable string (more later)– StringBuffer buffer = new StringBuffer( "Hello there" );

– Can initialize Strings with StringBuffers

s7 = new String( myStringBuffer )

Page 7: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

Class StringConstructors

1. main

1.1 Initialize arrays

1.2 Declarations

1.3 Constructors

1// Fig. 10.1: StringConstructors.java

2// This program demonstrates the String class constructors.

3import javax.swing.*;

4

5public class StringConstructors {

6 public static void main( String args[] )

7 {

8 char charArray[] = { 'b', 'i', 'r', 't', 'h', ' ',

9 'd', 'a', 'y' };

10 byte byteArray[] = { (byte) 'n', (byte) 'e', (byte) 'w',

11 (byte) ' ', (byte) 'y', (byte) 'e',

12 (byte) 'a', (byte) 'r' };

13 StringBuffer buffer;

14 String s, s1, s2, s3, s4, s5, s6, s7, output;

15

16

17 s = new String( "hello" );

18 buffer =

19 new StringBuffer( "Welcome to Java Programming!" );

20

21 // use the String constructors

22 s1 = new String();

23 s2 = new String( s );

24 s3 = new String( charArray );

25 s4 = new String( charArray, 6, 3 );

26 s5 = new String( byteArray, 4, 4 );

27 s6 = new String( byteArray );

28 s7 = new String( buffer );

29

Page 8: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

2. Append output

3. GUI

Program Output

30 output = "s1 = " + s1 +31 "\ns2 = " + s2 +32 "\ns3 = " + s3 +33 "\ns4 = " + s4 +

34 "\ns5 = " + s5 +

35 "\ns6 = " + s6 +

36 "\ns7 = " + s7;

37

38 JOptionPane.showMessageDialog( null, output,

39 "Demonstrating String Class Constructors",

40 JOptionPane.INFORMATION_MESSAGE );

41

42 System.exit( 0 );

43 }

44 }

Page 9: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

10.4String Methods length, charAt and getChars

• String methods– s1.length()

• Returns length of string• Be careful, Strings do not have an instance variable length like arrays– s1.length is an error

– s1.charAt( index )• Returns char at location index• Numbered like arrays (start at position 0)

– s1.getChars( start, end, charArray, offset )

• Copies characters in s1 from index start to index end to location offset in charArray

Page 10: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

Class StringMisc

1. main

1.1 Initialization

1.2 Output

2. s1.length()

3. Loop and print reversed characters

1 // Fig. 10.2: StringMisc.java2 // This program demonstrates the length, charAt and getChars3 // methods of the String class.4 //5 // Note: Method getChars requires a starting point6 // and ending point in the String. The starting point is the7 // actual subscript from which copying starts. The ending point8 // is one past the subscript at which the copying ends.9 import javax.swing.*;1011 public class StringMisc {12 public static void main( String args[] )13 {14 String s1, output;15 char charArray[];1617 s1 = new String( "hello there" );18 charArray = new char[ 5 ];1920 // output the string21 output = "s1: " + s1;2223 // test the length method24 output += "\nLength of s1: " + s1.length();2526 // loop through the characters in s1 and display reversed27 output += "\nThe string reversed is: ";2829 for ( int i = s1.length() - 1; i >= 0; i-- )30 output += s1.charAt( i ) + " ";

Page 11: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

4. getChars

5. GUI

Program Output

34 s1.getChars( 0, 5, charArray, 0 );

35 output += "\nThe character array is: ";

36

37 for ( int i = 0; i < charArray.length; i++ )

38 output += charArray[ i ];

39

40 JOptionPane.showMessageDialog( null, output,

41 "Demonstrating String Class Constructors",

42 JOptionPane.INFORMATION_MESSAGE );

43

44 System.exit( 0 );

45 }

46 }

33 // copy characters from string into char array

Page 12: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

10.5Comparing Strings

• Comparing Strings– All characters represented as numeric codes (Appendix D)

– When computer compares strings, compares numeric codes• Lexicographical comparison - compare Unicode values

• Lowercase different than uppercase

• Comparison methods– s1.equals( "Hi" )

• Returns true if s1 equal to "Hi"• Capitalization (case) matters

– s1.equalsIgnoreCase( otherString )• Tests for equality, case does not matter• "hello" equal to "HELLO"

Page 13: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

10.5Comparing Strings

• Comparison methods– s1.compareTo( otherString )

• Uses lexicographical comparison

• Returns 0 if strings equal

• Returns negative number if s1 < otherString• Returns positive number if s1 > otherString

– s1.regionMatches( offset, otherString, start, end )

• Compares s1 from location offset to otherString from location start to end

– s1.regionMatches( ignoreCase, offset, otherString, start, end )

• As above, but if ignoreCase is true, case is ignored

Page 14: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

10.5Comparing Strings

• == operator– When used with primitive data types, returns true if equal

– When used with references, returns true if point to same location in memory

– Remember, Java treats all anonymous String objects with same contents as one object with many referencess1 = "hello"; //uses anonymous object

s2 = new String( "hello" );

s1 == "hello"; //true

s2 == "hello"; //false

Page 15: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

29 else

Class StringCompare

1. main

1.1 Initialization

1.2 Append output

2. Tests for equality

1 // Fig. 10.3: StringCompare2 // This program demonstrates the methods equals, 3 // equalsIgnoreCase, compareTo, and regionMatches 4 // of the String class.5 import javax.swing.JOptionPane;67 public class StringCompare {8 public static void main( String args[] )9 {10 String s1, s2, s3, s4, output;1112 s1 = new String( "hello" );13 s2 = new String( "good bye" );14 s3 = new String( "Happy Birthday" );15 s4 = new String( "happy birthday" );1617 output = "s1 = " + s1 + "\ns2 = " + s2 +18 "\ns3 = " + s3 + "\ns4 = " + s4 + "\n\n";1920 // test for equality21 if ( s1.equals( "hello" ) )22 output += "s1 equals \"hello\"\n";23 else24 output += "s1 does not equal \"hello\"\n"; 25

26 // test for equality with ==2727 if ( s1 == "hello" )28 output += "s1 equals \"hello\"\n";

30 output += "s1 does not equal \"hello\"\n";

s1 will fail this test because it was not initialized with an anonymous String object.

Page 16: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

2. Tests for equality

3. compareTo

4. regionMatches

3132 // test for equality--ignore case33 if ( s3.equalsIgnoreCase( s4 ) )34 output += "s3 equals s4\n";35 else36 output += "s3 does not equal s4\n";3738 // test compareTo39 output +=40 "\ns1.compareTo( s2 ) is " + s1.compareTo( s2 ) +41 "\ns2.compareTo( s1 ) is " + s2.compareTo( s1 ) +42 "\ns1.compareTo( s1 ) is " + s1.compareTo( s1 ) +43 "\ns3.compareTo( s4 ) is " + s3.compareTo( s4 ) +44 "\ns4.compareTo( s3 ) is " + s4.compareTo( s3 ) +45 "\n\n";4647 // test regionMatches (case sensitive)48 if ( s3.regionMatches( 0, s4, 0, 5 ) )49 output += "First 5 characters of s3 and s4 match\n";50 else51 output +=52 "First 5 characters of s3 and s4 do not match\n";5354 // test regionMatches (ignore case)55 if ( s3.regionMatches( true, 0, s4, 0, 5 ) )56 output += "First 5 characters of s3 and s4 match";57 else58 output +=59 "First 5 characters of s3 and s4 do not match";60

Page 17: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

5. GUI

Program Output

61 JOptionPane.showMessageDialog( null, output,

62 "Demonstrating String Class Constructors",

63 JOptionPane.INFORMATION_MESSAGE );

64

65 System.exit( 0 );

66 }

67 }

Using equals, ==, and equalsIgnoreCase

Page 18: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

10.6String Method hashCode

• Hash table– Fast access to data

– Stores information using a calculation that makes a hash code

• Code used to choose location to store object in table

– To retrieve information, use same calculation• Hash code determined, go to that location of table

• Get original value

– Every object can be stored in a hash table

– Class Object defines method hashCode• Inherited by all subclasses • hashCode overridden in class String to provide a good

hash code distribution

Page 19: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

Class StringHashCode

1. main

1.1 Initialization

2. hashCode

3. GUI

Program Output

1 // Fig. 10.5: StringHashCode.java12 // This program demonstrates the method 3 // hashCode of the String class.4 import javax.swing.*;56 public class StringHashCode {7 public static void main( String args[] )8 {9 String s1 = "hello",10 s2 = "Hello";1112 String output =13 "The hash code for \"" + s1 + "\" is " +14 s1.hashCode() + 15 "\nThe hash code for \"" + s2 + "\" is " +16 s2.hashCode();1718 JOptionPane.showMessageDialog( null, output,19 "Demonstrating String Method hashCode",20 JOptionPane.INFORMATION_MESSAGE );2122 System.exit( 0 );23 }24 }

Page 20: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

10.7Locating Characters and Substrings in Strings

• Search methods– s1.indexOf( integerRep )

• integerRep - integer representation of a character ('z')

• Returns index of the first occurrence of the character in the string

– Returns -1 if not found

– s1.indexOf( integerRep, startSearch )• As above, but begins search at position startSearch

– s1.lastIndexOf( integerRep )• Returns index of last occurrence of character in string

– s1.lastIndexOf( integerRep, startSearch )• As above, but searches backwards from position startSearch

Page 21: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

10.7Locating Characters and Substrings in Strings

• Search methods (continued)– Can use indexOf and lastIndexOf with Strings

– Search for substrings within a string• Identical usage as with characters, i.e.

s1.indexOf( "hi" )

s1.lastIndexOf( "this", 24 )

Page 22: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

Class StringIndexMethods

1. main

1.1 Initialization

2. indexOf (two versions)

3. lastIndexOf (two versions)

1 // Fig. 10.6: StringIndexMethods.java

2 // This program demonstrates the String

3 // class index methods.

4 import javax.swing.*;

5

6

7 public class StringIndexMethods {

8 public static void main( String args[] )

9 {

10 String letters = "abcdefghijklmabcdefghijklm";

11 String output;

12

13 // test indexOf to locate a character in a string

14 output = "'c' is located at index " +

15 letters.indexOf( 'c' );

16

17 output += "\n'a' is located at index " +

18 letters.indexOf( 'a', 1 );

19

20 output += "\n'$' is located at index " +

21 letters.indexOf( '$' );

22

23 // test lastIndexOf to find a character in a string

24 output += "\n\nLast 'c' is located at index " +

25 letters.lastIndexOf( 'c' );

26

27 output += "\nLast 'a' is located at index " +

28 letters.lastIndexOf( 'a', 25 );

29

Page 23: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

4. indexOf (two versions)

5. lastIndexOf (two versions)

6. GUI

30 output += "\nLast '$' is located at index " +31 letters.lastIndexOf( '$' );3233 // test indexOf to locate a substring in a string34 output += "\n\n\"def\" is located at index " +35 letters.indexOf( "def" );3637 output += "\n\"def\" is located at index " +38 letters.indexOf( "def", 7 );3940 output += "\n\"hello\" is located at index " +41 letters.indexOf( "hello" );4243 // test lastIndexOf to find a substring in a string44 output += "\n\nLast \"def\" is located at index " +45 letters.lastIndexOf( "def" );4647 output += "\nLast \"def\" is located at index " +48 letters.lastIndexOf( "def", 25 );4950 output += "\nLast \"hello\" is located at index " +51 letters.lastIndexOf( "hello" );5253 JOptionPane.showMessageDialog( null, output,54 "Demonstrating String Class \"index\" Methods",55 JOptionPane.INFORMATION_MESSAGE );5657 System.exit( 0 );58 }59 }60

Page 24: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

Program Output

Page 25: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

10.8Extracting Substrings from Strings

• substring methods– Return a String object– s1.substring( startIndex )

• Returns a substring from startIndex to the end of the string

– s1.substring( start, end )• Returns a substring from location start up to, but not

including, location end

– If index out of bounds, StringIndexOutOfBoundsException generated

Page 26: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

Class Substring

1. main

1.1 Initialization

2. substring methods

3. GUI

Program Output

1 // Fig. 10.7: SubString.java2 // This program demonstrates the3 // String class substring methods.4 import javax.swing.*;56 public class SubString {7 public static void main( String args[] )8 {9 String letters = "abcdefghijklmabcdefghijklm";10 String output;1112 // test substring methods13 output = "Substring from index 20 to end is " +14 "\"" + letters.substring( 20 ) + "\"\n";1516 output += "Substring from index 0 up to 6 is " +17 "\"" + letters.substring( 0, 6 ) + "\"";1819 JOptionPane.showMessageDialog( null, output,20 "Demonstrating String Class Substring Methods",21 JOptionPane.INFORMATION_MESSAGE );2223 System.exit( 0 );24 }25 }

Page 27: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

10.9Concatenating Strings

• Method concat– Concatenates two Strings, returns new String object

– Original Strings are not modified– s1.concat( s2 )

• Returns concatenation of s1 and s2• If no argument, returns s1

Page 28: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

Class StringConcat

1. main

1.1 Initialization

2. concat

3. GUI

1 // Fig. 10.8: StringConcat.java

2 // This program demonstrates the String class concat method.

3 // Note that the concat method returns a new String object. It

4 // does not modify the object that invoked the concat method.

5 import javax.swing.*;

6

7 public class StringConcat {

8 public static void main( String args[] )

9 {

10 String s1 = new String( "Happy " ),

11 s2 = new String( "Birthday" ),

12 output;

13

14 output = "s1 = " + s1 +

15 "\ns2 = " + s2;

16

17 output += "\n\nResult of s1.concat( s2 ) = " +

18 s1.concat( s2 );

19

20 output += "\ns1 after concatenation = " + s1;

21

22 JOptionPane.showMessageDialog( null, output,

23 "Demonstrating String Method concat",

24 JOptionPane.INFORMATION_MESSAGE );

25

26 System.exit( 0 );

27 }

28 }

Page 29: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

Program Output

Page 30: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

10.10 Miscellaneous String Methods

• Miscellaneous methods– s1.replace( char1, char2 )

• Returns a new String, replacing all instances of char1 with char2

– Use integer representations: 'z', '1', etc.

– Original String not changed

• If no instances of char1, original string returned

– s1.toUpperCase()• Returns new String object with all letters capitalized

– If no changes needed, original string returned

• Original string unchanged• s1.toLowerCase() similar

Page 31: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

10.10 Miscellaneous String Methods

• Miscellaneous methods (continued)– s1.trim()

• Returns new String, removing all whitespace characters at beginning or end

• Original unchanged

– s1.toString()• All objects can be converted to Strings with toString

– s1.toCharArray()• Creates a new character array containing copy of characters in s1

Page 32: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

Class StringMisc2

1. main

1.1 Initialization

2. replace

3. toUpperCase and toLowerCase

4. trim

1 // Fig. 10.9: StringMisc2.java

2 // This program demonstrates the String methods replace,

3 // toLowerCase, toUpperCase, trim, toString and toCharArray

4 import javax.swing.*;

5

6 public class StringMisc2 {

7 public static void main( String args[] )

8 {

9 String s1 = new String( "hello" ),

10 s2 = new String( "GOOD BYE" ),

11 s3 = new String( " spaces " ),

12 output;

13

14 output = "s1 = " + s1 +

15 "\ns2 = " + s2 +

16 "\ns3 = " + s3;

17

18 // test method replace

19 output += "\n\nReplace 'l' with 'L' in s1: " +

20 s1.replace( 'l', 'L' );

21

22 // test toLowerCase and toUpperCase

23 output +=

24 "\n\ns1.toUpperCase() = " + s1.toUpperCase() +

25 "\ns2.toLowerCase() = " + s2.toLowerCase();

26

27 // test trim method

28 output += "\n\ns3 after trim = \"" + s3.trim() + "\"";

29

Page 33: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

5. toString

6. toCharArray

7. GUI

30 // test toString method

31 output += "\n\ns1 = " + s1.toString();

32

33 // test toCharArray method

34 char charArray[] = s1.toCharArray();

35

36 output += "\n\ns1 as a character array = ";

37

38 for ( int i = 0; i < charArray.length; ++i )

39 output += charArray[ i ];

40

41 JOptionPane.showMessageDialog( null, output,

42 "Demonstrating Miscellaneous String Methods",

43 JOptionPane.INFORMATION_MESSAGE );

44

45 System.exit( 0 );46 }

47 }

Page 34: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

Program Output

Page 35: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

10.11 Using String Method valueOf

• static methods of class String– Take arguments and convert them to Strings– String.valueOf( charArray )

• Returns new String object containing characters in charArray

– String.valueOf( charArray, startIndex, numChars )

• As above, but starts from position startIndex and copies numChars characters

– Other versions of valueOf take boolean, char, int, long, float, double, and Object• Objects converted to Strings with toString

Page 36: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

Class StringValueOf

1. main

1.1 Initialization

2. valueOf

1 // Fig. 10.10: StringValueOf.java

2 // This program demonstrates the String class valueOf methods.

3 import javax.swing.*;

4

5 public class StringValueOf {

6 public static void main( String args[] )

7 {

8 char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' };

9 boolean b = true;

10 char c = 'Z';

11 int i = 7;

12 long l = 10000000;

13 float f = 2.5f;

14 double d = 33.333;

15

16 Object o = "hello"; // Assign to an Object reference

17 String output;

18

19 output = "char array = " + String.valueOf( charArray ) +

20 "\npart of char array = " +

21 String.valueOf( charArray, 3, 3 ) +

22 "\nboolean = " + String.valueOf( b ) +

23 "\nchar = " + String.valueOf( c ) +

24 "\nint = " + String.valueOf( i ) +

25 "\nlong = " + String.valueOf( l ) +

26 "\nfloat = " + String.valueOf( f ) +

27 "\ndouble = " + String.valueOf( d ) +

28 "\nObject = " + String.valueOf( o );

29

Page 37: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

3. GUI

Program Output

30 JOptionPane.showMessageDialog( null, output,

31 "Demonstrating String Class valueOf Methods",

32 JOptionPane.INFORMATION_MESSAGE );

33

34 System.exit( 0 );

35 }

36 }

Page 38: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

10.12 String Method intern

• Method intern– Improves string comparison performance

– Returns reference guaranteed to have same contents• Multiple interns generate references to same object

– Strings can be compared with == (same location in memory) instead of equals

• Much faster than comparing character by character

Page 39: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

Class StringIntern

1. main

1.1 Initialization

2. Comparisons using ==

2.1 Comparisons using equals

1 // Fig. 10.11: StringIntern.java

2 // This program demonstrates the intern method

3 // of the String class.

4 import javax.swing.*;

5

6 public class StringIntern {

7 public static void main( String args[] )

8 {

9 String s1, s2, s3, s4, output;

10

11 s1 = new String( "hello" );

12 s2 = new String( "hello" );

13

14 // Test strings to determine if they are the same

15 // String object in memory.

16 if ( s1 == s2 )

17 output =

18 "s1 and s2 are the same object in memory";

19 else

20 output =

21 "s1 and s2 are not the same object in memory";

22

23 // Test strings for equality of contents

24 if ( s1.equals( s2 ) )

25 output += "\ns1 and s2 are equal";

26 else

27 output += "\ns1 and s2 are not equal";

28

Page 40: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

3. intern

4. Comparisons using ==

29 // Use String intern method to get a unique copy of30 // "hello" referred to by both s3 and s4.3131 s3 = s1.intern();32 s4 = s2.intern();333435 // Test strings to determine if they are the same36 // String object in memory.37 if ( s3 == s4 )38 output +=39 "\ns3 and s4 are the same object in memory";40 else41 output +=42 "\ns3 and s4 are not the same object in memory";4344 // Determine if s1 and s3 refer to the same object45 if ( s1 == s3 )46 output +=47 "\ns1 and s3 are the same object in memory";48 else49 output +=50 "\ns1 and s3 are not the same object in memory";5152 // Determine if s2 and s4 refer to the same object53 if ( s2 == s4 )54 output +=55 "\ns2 and s4 are the same object in memory";56 else57 output +=58 "\ns2 and s4 are not the same object in memory";59

Because s1 and s2 have the same contents, s3 and s4 are references to the same object in memory.

Page 41: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

4. Comparisons using ==

5. GUI

Program Output

60 // Determine if s1 and s4 refer to the same object

61 if ( s1 == s4 )

62 output +=

63 "\ns1 and s4 are the same object in memory";

64 else

65 output +=

66 "\ns1 and s4 are not the same object in memory";67

68 JOptionPane.showMessageDialog( null, output,

69 "Demonstrating String Method intern",

70 JOptionPane.INFORMATION_MESSAGE );

71

72 System.exit( 0 );

73 }

74 }

75

s1 and s2 both contain "hello" but are not the same object.

s3 and s4 were interned from s1 and s2, and are the same object in memory.

Page 42: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

10.13 StringBuffer Class

• Class String– Once a String is created, it cannot be changed

• Class StringBuffer– Can create modifiable Strings

– Capable of storing number of characters specified by capacity

• If capacity exceeded, automatically expands to hold new characters

– Can use + and += operators

Page 43: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

10.14 StringBuffer Constructors

• StringBuffer constructors– buf1 = new StringBuffer();

• Creates empty StringBuffer, capacity of 16 characters

– buf2 = new StringBuffer( capacity );• Creates empty StringBuffer with specified capacity

– but3 = new StringBuffer( myString );• Creates a StringBuffer containing myString, with

capacity myString.length() + 16

Page 44: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

Class StringBuffer Constructors

1. main

1.1 Initialization (note use of constructors)

2. Output

3. GUI

1 // Fig. 10.12: StringBufferConstructors.java

2 // This program demonstrates the StringBuffer constructors.

3 import javax.swing.*;

4

5 public class StringBufferConstructors {

6 public static void main( String args[] )

7 {

8 StringBuffer buf1, buf2, buf3;

9

10 buf1 = new StringBuffer();

11 buf2 = new StringBuffer( 10 );

12 buf3 = new StringBuffer( "hello" );

13

14 String output =

15 "buf1 = " + "\"" + buf1.toString() + "\"" +

16 "\nbuf2 = " + "\"" + buf2.toString() + "\"" +

17 "\nbuf3 = " + "\"" + buf3.toString() + "\"";

18

19 JOptionPane.showMessageDialog( null, output,

20 "Demonstrating StringBuffer Class Constructors",

21 JOptionPane.INFORMATION_MESSAGE );

22

23 System.exit( 0 );

24 }

25 }

Page 45: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

Program Output

Page 46: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

10.15 StringBuffer Methods length, capacity, setLength and

ensureCapacity• StringBuffer methods

– length - returns length– capacity - returns capacity– setLength( newLength )

• Changes length of StringBuffer to newLength• If too long, truncates excess characters

• If too short, fills with null character (numeric representation of 0)

– ensureCapacity( size )• Expands capacity to a minimum of size• If size less than current capacity, then capacity is unchanged

Page 47: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

Class StringBufferCapLen

1. main

1.1 Initialization

2. length

2.1 capacity

3. ensureCapacity

3.1 setLength

4. GUI

1 // Fig. 10.13: StringBufferCapLen.java2 // This program demonstrates the length and3 // capacity methods of the StringBuffer class.4 import javax.swing.*;56 public class StringBufferCapLen {7 public static void main( String args[] )8 {9 StringBuffer buf =10 new StringBuffer( "Hello, how are you?" );1112 String output = "buf = " + buf.toString() +13 "\nlength = " + buf.length() +14 "\ncapacity = " + buf.capacity();1516 buf.ensureCapacity( 75 );17 output += "\n\nNew capacity = " + buf.capacity();1819 buf.setLength( 10 );20 output += "\n\nNew length = " + buf.length() +21 "\nbuf = " + buf.toString();2223 JOptionPane.showMessageDialog( null, output,24 "StringBuffer length and capacity Methods",25 JOptionPane.INFORMATION_MESSAGE );262728 System.exit( 0 );29 }30 }

Page 48: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

Program Output

Page 49: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

10.16 StringBuffer Methods charAt, setCharAt, getChars and

reverse• StringBuffer methods

– charAt( index ) - returns character at position index– setCharAt( index, char )

• Sets character at position index to char

– getChars( start, end, charArray, loc )• Copies from position start up to (not including) end into

location loc in charArray

– reverse - reverses contents of StringBuffer

Page 50: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

Class StringBufferChars

1. main

1.1 Initialization

2. charAt

3. getChars

4. setCharAt

5. reverse

1 // Fig. 10.14: StringBufferChars.java

2 // The charAt, setCharAt, getChars, and reverse methods

3 // of class StringBuffer.

4 import javax.swing.*;

5

6 public class StringBufferChars {

7 public static void main( String args[] )

8 {

9 StringBuffer buf = new StringBuffer( "hello there" );

10

11 String output = "buf = " + buf.toString() +

12 "\nCharacter at 0: " + buf.charAt( 0 ) +

13 "\nCharacter at 4: " + buf.charAt( 4 );

14

15 char charArray[] = new char[ buf.length() ];

16 buf.getChars( 0, buf.length(), charArray, 0 );

17 output += "\n\nThe characters are: ";

18

19 for ( int i = 0; i < charArray.length; ++i )

20 output += charArray[ i ];

21

22 buf.setCharAt( 0, 'H' );

23 buf.setCharAt( 6, 'T' );

24 output += "\n\nbuf = " + buf.toString();

25

26 buf.reverse();

27 output += "\n\nbuf = " + buf.toString();

28

Page 51: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

6. GUI

Program Output

34 System.exit( 0 );

35 }

36 }

29 JOptionPane.showMessageDialog( null, output,

30 "Demonstrating StringBuffer Character Methods",

31 JOptionPane.INFORMATION_MESSAGE );

32

33

Page 52: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

10.17 StringBuffer append Methods

• 10 overloaded append methods– Versions for each of the primitive data types, character arrays, Strings, and Objects (using toString)

– StringBuffers and append used by compiler to concatenate Strings

String s = "BC" + 22;

actually performed as

new StringBuffer( "BC").append(22).toString();• StringBuffer created with String "BC" as contents

• Integer 22 appended to StringBuffer• StringBuffer converted to a String (toString)

• Result assigned to s

Page 53: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

Class StringBufferAppend

1. main

1.1 Initialization

2. append

1 // Fig. 10.15: StringBufferAppend.java2 // This program demonstrates the append3 // methods of the StringBuffer class.4 import javax.swing.*;56 public class StringBufferAppend {7 public static void main( String args[] )8 {9 Object o = "hello"; 10 String s = "good bye"; 11 char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' };12 boolean b = true;13 char c = 'Z';14 int i = 7;15 long l = 10000000;16 float f = 2.5f;17 double d = 33.333;18 StringBuffer buf = new StringBuffer();1920 buf.append( o );21 buf.append( " " );2223 buf.append( s );24 buf.append( " " );25 buf.append( charArray );26 buf.append( " " );27 buf.append( charArray, 0, 3 );28 buf.append( " " );29 buf.append( b );30 buf.append( " " );

Page 54: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

2. append

3. GUI

Program Output

31 buf.append( c );32 buf.append( " " );33 buf.append( i );34 buf.append( " " );

35 buf.append( l );

36 buf.append( " " );

37 buf.append( f );

38 buf.append( " " );

39 buf.append( d );

40

41 JOptionPane.showMessageDialog( null,

42 "buf = " + buf.toString(),

43 "Demonstrating StringBuffer append Methods",

44 JOptionPane.INFORMATION_MESSAGE );

45

46 System.exit( 0 );

47 }

48 }

Page 55: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

10.18 StringBuffer Insertion and Deletion Methods

• Nine overloaded insert methods– Insert various data at any position in StringBuffer– insert( index, data )

• Inserts data right before position index• index must be greater than or equal to 0

• delete methods– delete( start, end )

• Deletes from start up to (not including) end

– deleteCharAt( index )• Deletes character at index

Page 56: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

Class StringBufferInsert

1. main

1.1 Initialization

2. insert

1 // Fig. 10.16: StringBufferInsert.java2 // This program demonstrates the insert and delete3 // methods of class StringBuffer.4 import javax.swing.*;56 public class StringBufferInsert {7 public static void main( String args[] )8 {9 Object o = "hello"; 10 String s = "good bye"; 11 char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' };12 boolean b = true;13 char c = 'K';14 int i = 7;15 long l = 10000000;16 float f = 2.5f;17 double d = 33.333;18 StringBuffer buf = new StringBuffer();1920 buf.insert( 0, o );21 buf.insert( 0, " " );22 buf.insert( 0, s );23 buf.insert( 0, " " );24 buf.insert( 0, charArray );25 buf.insert( 0, " " );26 buf.insert( 0, b );2728 buf.insert( 0, " " );29 buf.insert( 0, c );30 buf.insert( 0, " " );

Page 57: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

2. insert

3. deleteCharAt

4. delete

31 buf.insert( 0, i );32 buf.insert( 0, " " );33 buf.insert( 0, l );34 buf.insert( 0, " " );

35 buf.insert( 0, f );

36 buf.insert( 0, " " );

37 buf.insert( 0, d );

38

39 String output = "buf after inserts:\n" + buf.toString();

40

41 buf.deleteCharAt( 10 ); // delete 5 in 2.5

42 buf.delete( 2, 6 ); // delete .333 in 33.333

43

44 output += "\n\nbuf after deletes:\n" + buf.toString();

45

46 JOptionPane.showMessageDialog( null, output,

47 "Demonstrating StringBufferer Inserts and Deletes",

48 JOptionPane.INFORMATION_MESSAGE );

49

50 System.exit( 0 );

51 }

52 }

Page 58: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

Program Output

Page 59: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

10.19 Character Class Examples

• Classes to treat primitive variables as objects– type wrappers: Boolean, Character, Double, Float, Byte, Short, Integer and Long

• All but Boolean and Character derive from Number• Objects of these classes can be used anywhere an Object or Number is expected

– In this section, study class Character (for information on all type-wrappers see java.lang package in API)

• Class Character

Page 60: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

10.19 Character Class Examples

• Class Character static methods– Let c be a char– Character.isDefined( c )

• Returns true if character defined in Unicode character set

– Character.isJavaIdentifierStart ( c )• Returns true if character can be used as first letter of an

identifier (letter, underscore ( _ ) or dollar sign ( $ ) )

– Character.isJavaIdentifierPart( c ) • Returns true if character can be used in an identifier (letter,

digit, underscore, or dollar sign)

– Character.isDigit( c )– Character.isLetter( c )

• Character.isLetterOrDigit( c )

Page 61: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

10.19 Character Class Examples

• Class Character static methods– Character.isLowerCase( c )

• Character.toLowerCase( c )– Returns converted character

– Returns original if no change needed

– Character.isUpperCase( c )• Character.toUpperCase( c )

– Character.digit( c, radix )• Converts character c into a digit of base radix

– Character.forDigit( digit, radix )• Converts integer digit into a character using base radix

Page 62: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

10.19 Character Class Examples

• Non-static methods of class Character– c1.charValue()

• Returns char value stored in Character object c1

– c1.toString()• Returns String representation of c1

– c1.hashCode()• Performs hashCode calculations

• Remember, used to store objects in hash tables for fast lookup

– c1.equals( c2 )• Determines if c1 has same contents as c2

Page 63: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

Class StaticCharMethods

1. main

1.1 Declarations

2. Constructor

2.1 GUI

1 // Fig. 10.17: StaticCharMethods.java

2 // Demonstrates the static character testing methods

3 // and case conversion methods of class Character

4 // from the java.lang package.

5 import javax.swing.*;

6 import java.awt.*;

7 import java.awt.event.*;

8

9 public class StaticCharMethods extends JFrame {

10 private char c;

11 private JLabel prompt;

12 private JTextField input;

13 private JTextArea outputArea;

14

15 public StaticCharMethods()

16 {

17 super( "Static Character Methods" );

18

19 Container container = getContentPane();

20 container.setLayout( new FlowLayout() );

21

22 prompt =

23 new JLabel( "Enter a character and press Enter" );

24 container.add( prompt );

25

26 input = new JTextField( 5 );

27 input.addActionListener(

28 new ActionListener() {

29 public void actionPerformed( ActionEvent e )

Page 64: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

2.2 Event handler

2.3 GUI

3. buildOutput

3.1 static method calls

32 c = s.charAt( 0 );

34 }

35 }36 );37 container.add( input );3839 outputArea = new JTextArea( 10, 20 );40 container.add( outputArea );4142 setSize( 300, 250 ); // set the window size43 show(); // show the window44 }454647 public void buildOutput()48 {49 outputArea.setText(50 "is defined: " + Character.isDefined( c ) +51 "\nis digit: " + Character.isDigit( c ) +52 "\nis Java letter: " +53 Character.isJavaIdentifierStart( c ) +54 "\nis Java letter or digit: " +55 Character.isJavaIdentifierPart( c ) +56 "\nis letter: " + Character.isLetter( c ) +57 "\nis letter or digit: " +58 Character.isLetterOrDigit( c ) +59 "\nis lower case: " + Character.isLowerCase( c ) +

30 {

31 String s = e.getActionCommand();

33 buildOutput();

Page 65: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

3.1 static method calls

4. main

6463 }

67 StaticCharMethods application = new StaticCharMethods();

68

69 application.addWindowListener(

70 new WindowAdapter() {

71 public void windowClosing( WindowEvent e )

72 {

73 System.exit( 0 );

74 }

75 }

76 );

77 }

60 "\nis upper case: " + Character.isUpperCase( c ) +61 "\nto upper case: " + Character.toUpperCase( c ) +62 "\nto lower case: " + Character.toLowerCase( c ) );

65 public static void main( String args[] )66 {

Page 66: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

Program Output

Page 67: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

10.20 Class StringTokenizer

• Tokenization– Breaking statements into pieces

– Class StringTokenizer breaks a String into component tokens

• Tokens separated by delimiters, typically whitespace characters

• Other characters may be used

• Class StringTokenizer– One constructor: StringTokenizer( myString )

• Initialize StringTokenizer with a String• Default delimiter " \n\t\r" (space, newline, tab, carriage

return)

• Other constructors allow you to specify delimiter

Page 68: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

10.20 Class StringTokenizer

• Methods– countTokens()

• Determines number of tokens in String

– nextToken()• Returns next token as a String

– nextToken( delimiterString )• Changes delimiter while tokenizing a String

– hasMoreTokens()• Determines if there are more tokens to be tokenized

Page 69: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

Class TokenTest

1. Constructor

1.1 GUI

1 // Fig. 10.20: TokenTest.java

2 // Testing the StringTokenizer class of the java.util package

3 import javax.swing.*;

4 import java.util.*;

5 import java.awt.*;

6 import java.awt.event.*;

7

8 public class TokenTest extends JFrame {

9 private JLabel prompt;

10 private JTextField input;

11 private JTextArea output;

12

13 public TokenTest()

14 {

15 super( "Testing Class StringTokenizer" );

16

17 Container c = getContentPane();

18 c.setLayout( new FlowLayout() );

19

20 prompt =

21 new JLabel( "Enter a sentence and press Enter" );

22 c.add( prompt );

23

24 input = new JTextField( 20 );

25 input.addActionListener(

26 new ActionListener() {

27

28

Page 70: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

1.2 Event handler

1.2.1 Tokenize String

1.3 GUI

2. main

29 public void actionPerformed( ActionEvent e )30 { 31 String stringToTokenize = e.getActionCommand();32 StringTokenizer tokens =33 new StringTokenizer( stringToTokenize );3435 output.setText( "Number of elements: " +36 tokens.countTokens() +37 "\nThe tokens are:\n" );383939 while ( tokens.hasMoreTokens() )40 output.append( tokens.nextToken() + "\n" );41 }42 }43 );44 c.add( input );4546 output = new JTextArea( 10, 20 );47 output.setEditable( false );48 c.add( new JScrollPane( output ) );4950 setSize( 275, 260 ); // set the window size51 show(); // show the window52 }5354 public static void main( String args[] )55 {56 TokenTest app = new TokenTest();5758 app.addWindowListener(59 new WindowAdapter() {60 public void windowClosing( WindowEvent e )

Notice loop to tokenize the string

Page 71: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

Program Output

61 {

62 System.exit( 0 );

63 }

64 }

65 );

66 }

67 }

Page 72: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

10.21 A Card Shuffling and Dealing Simulation

• Create card shuffling/dealing simulation– Create class Card with variables face and suit– Create deck, an array of Cards

– To shuffle cards• Loop through deck array

• Generate random number (0-51) and swap current card with that card

– To deal cards, walk through deck array• After all cards are dealt, ask user to shuffle again

Page 73: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

Class DeckOfCards

1. Instance variables

1.1 Constructor

1.2 Initialize arrays

1.3 Create deck array

1.4 Initialize deck

1 // Fig. 10.21: DeckOfCards.java2 // Card shuffling and dealing program3 import javax.swing.*;4 import java.awt.*;5 import java.awt.event.*;67 public class DeckOfCards extends JFrame {8 private Card deck[];9 private int currentCard;10 private JButton dealButton, shuffleButton;11 private JTextField displayCard;12 private JLabel status;1314 public DeckOfCards()15 {16 super( "Card Dealing Program" );1718 String faces[] = { "Ace", "Deuce", "Three", "Four", 19 "Five", "Six", "Seven", "Eight", 20 "Nine", "Ten", "Jack", "Queen",21 "King" };22 String suits[] = { "Hearts", "Diamonds",23 "Clubs", "Spades" };2425 deck = new Card[ 52 ];26 currentCard = -1;27 28 for ( int i = 0; i < deck.length; i++ ) 29 deck[ i ] = new Card( faces[ i % 13 ],30 suits[ i / 13 ] );

Page 74: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

2. GUI

2.1 Event handlers

3. GUI

3132 Container c = getContentPane();33 c.setLayout( new FlowLayout() ); 3435 dealButton = new JButton( "Deal card" );36 dealButton.addActionListener(37 new ActionListener() {38 public void actionPerformed( ActionEvent e )39 {40 Card dealt = dealCard();414243 if ( dealt != null ) {44 displayCard.setText( dealt.toString() );45 status.setText( "Card #: " + currentCard );46 }47 else {48 displayCard.setText(49 "NO MORE CARDS TO DEAL" );50 status.setText(51 "Shuffle cards to continue" );52 }53 }54 }55 );56 c.add( dealButton );5758 shuffleButton = new JButton( "Shuffle cards" );59 shuffleButton.addActionListener(60 new ActionListener() {

Page 75: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

3.1 Event handler

4. GUI

5. shuffle

67 }68 );69 c.add( shuffleButton );7071 displayCard = new JTextField( 20 );72 displayCard.setEditable( false );73 c.add( displayCard );7475 status = new JLabel();76 c.add( status );7778 setSize( 275, 120 ); // set the window size79 show(); // show the window80 }8182 public void shuffle()83 {84 currentCard = -1;8586 for ( int i = 0; i < deck.length; i++ ) {

8787 int j = ( int ) ( Math.random() * 52 );88 Card temp = deck[ i ]; // swap89 deck[ i ] = deck[ j ]; // the90 deck[ j ] = temp; // cards

66 }

61 public void actionPerformed( ActionEvent e )62 {63 displayCard.setText( "SHUFFLING ..." );64 shuffle();65 displayCard.setText( "DECK IS SHUFFLED" );

Swap current Card with random Card.

Page 76: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

6. dealCard

7. main

91 }

92

93 dealButton.setEnabled( true );

94 }

95

96

97 public Card dealCard()

98 {

99 if ( ++currentCard < deck.length )100 return deck[ currentCard ];101 else { 102 dealButton.setEnabled( false );103 return null;104 }105 }106107 public static void main( String args[] )108 {109 DeckOfCards app = new DeckOfCards();110111 app.addWindowListener(112 new WindowAdapter() {113 public void windowClosing( WindowEvent e )114 {115 System.exit( 0 );116 }117 }118 );119 }120}

Page 77: Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

Class Card

Program Output

121122class Card {123 private String face;124 private String suit;125126 public Card( String f, String s )127 {128 face = f;129 suit = s;130 }131132 public String toString() { return face + " of " + suit; }133}