You are on page 1of 97

Chapter 11 Strings and Characters

Outline
11.1
Introduction
11.2
Fundamentals of Characters and Strings
11.3
Class String
11.3.1 String Constructors
11.3.2 String Methods length, charAt and getChars
11.3.3 Comparing Strings
11.3.4 Locating Characters and Substrings in Strings
11.3.5 Extracting Substrings from Strings
11.3.6 Concatenating Strings
11.3.7 Miscellaneous String Methods
11.3.8 String Method valueOf
11.4
Class StringBuffer
11.4.1 StringBuffer Constructors
11.4.2 StringBuffer Methods length, capacity,
setLength and ensureCapacity
11.4.3 StringBuffer Methods charAt, setCharAt,
getChars and reverse
2003 Prentice Hall, Inc. All rights reserved.

Chapter 11 Strings and Characters

11.4.4 StringBuffer append Methods


11.4.5 StringBuffer Insertion and Deletion Methods
11.5
Class Character
11.6
Class StringTokenizer
11.7
Card Shuffling and Dealing Simulation
11.8
Regular Expressions, Class Pattern and Class Matcher
11.9
(Optional Case Study) Thinking About Objects: Event
Handling

2003 Prentice Hall, Inc. All rights reserved.

11.1 Introduction
String and character processing

Class java.lang.String
Class java.lang.StringBuffer
Class java.lang.Character
Class java.util.StringTokenizer

2003 Prentice Hall, Inc. All rights reserved.

11.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

2003 Prentice Hall, Inc. All rights reserved.

11.3.1 String Constructors


Class String

Provides nine constructors

2003 Prentice Hall, Inc. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

Outline

// Fig. 11.1: StringConstructors.java


// String class constructors.
import javax.swing.*;
public class StringConstructors {

String defaultStringConstruct
constructor
instantiates empty
ors.java
string

public static void main( String args[] )


{
Constructor
char charArray[] = { 'b', 'i', 'r', 't', 'h', ' ', 'd', 'a', 'y' };
byte byteArray[] = { ( byte ) 'n', ( byte ) 'e',
Constructor
( byte ) 'w', ( byte ) ' ', ( byte ) 'y',
( byte ) 'e', ( byte ) 'a', ( byte ) 'r' };
String s = new String( "hello" );
// use
String
String
String
String
String
String

String constructors
s1 = new String();
s2 = new String( s );
s3 = new String( charArray );
s4 = new String( charArray, 6, 3 );
s5 = new String( byteArray, 4, 4 );
s6 = new String( byteArray );

LineString
17
copies
Linecharacter
18
copies
array

Line 19
Constructor copies
character-array subset
Line 20

Line
21array
Constructor copies
byte
Line 22
Constructor copies byte-array subset

2003 Prentice Hall, Inc.


All rights reserved.

23
24
25
26
27
28
29
30
31
32
33
34

// append Strings to output


String output = "s1 = " + s1 + "\ns2 = " + s2 + "\ns3 = " + s3 +
"\ns4 = " + s4 + "\ns5 = " + s5 + "\ns6 = " + s6;

Outline

JOptionPane.showMessageDialog( null, output,


"String Class Constructors", JOptionPane.INFORMATION_MESSAGE );

StringConstruct
ors.java

System.exit( 0 );
}
} // end class StringConstructors

2003 Prentice Hall, Inc.


All rights reserved.

11.3.2 String Methods length, charAt


and getChars
Method length
Determine String length
Like arrays, Strings always know their size
Unlike array, Strings do not have length instance variable

Method charAt
Get character at specific location in String

Method getChars

Get entire set of characters in String

2003 Prentice Hall, Inc. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

Outline

// Fig. 11.2: StringMiscellaneous.java


// This program demonstrates the length, charAt and getChars
// methods of the String class.
import javax.swing.*;

StringMiscellan
eous.java

public class StringMiscellaneous {

Line 16

public static void main( String args[] )


{
String s1 = "hello there";
char charArray[] = new char[ 5 ];

Line 21

String output = "s1: " + s1;


// test length method
output += "\nLength of s1: " + s1.length();

Determine number of
characters in String s1

// loop through characters in s1 and display reversed


output += "\nThe string reversed is: ";
for ( int count = s1.length() - 1; count >= 0; count-- )
output += s1.charAt( count ) + " ";

Append s1s characters


in reverse order to
String output

2003 Prentice Hall, Inc.


All rights reserved.

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

// copy characters from string into charArray


s1.getChars( 0, 5, charArray, 0 );
output += "\nThe character array is: ";
for ( int count = 0; count < charArray.length;
output += charArray[ count ];

Outline

Copy (some of) s1s


characters to charArray
StringMiscellan
eous.java
count++ )
Line 25

JOptionPane.showMessageDialog( null, output,


"String class character manipulation methods",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
} // end class StringMiscellaneous

2003 Prentice Hall, Inc.


All rights reserved.

11.3.3 Comparing Strings


Comparing String objects

Method equals
Method equalsIgnoreCase
Method compareTo
Method regionMatches

2003 Prentice Hall, Inc. All rights reserved.

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

Outline

// Fig. 11.3: StringCompare.java


// String methods equals, equalsIgnoreCase, compareTo and regionMatches.
import javax.swing.JOptionPane;

StringCompare.j
ava

public class StringCompare {


public static void main( String args[] )
{
String s1 = new String( "hello" ); // s1 is a copy of "hello"
String s2 = "goodbye";
String s3 = "Happy Birthday";
String s4 = "happy birthday";

Line 18
Line 24

String output = "s1 = " + s1 + "\ns2 = " + s2 + "\ns3 = " + s3 +


"\ns4 = " + s4 + "\n\n";
// test for equality
if ( s1.equals( "hello" ) ) // true
output += "s1 equals \"hello\"\n";
else
output += "s1 does not equal \"hello\"\n";

Method equals tests two


objects for equality using
lexicographical comparison
Equality operator (==) tests

// test for equality with ==


if both references refer to
if ( s1 == "hello" ) // false; they are not the same object
same object in memory
output += "s1 equals \"hello\"\n";
else
output += "s1 does not equal \"hello\"\n";

2003 Prentice Hall, Inc.


All rights reserved.

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

// test for equality (ignore case)


if ( s3.equalsIgnoreCase( s4 ) ) // true
output += "s3 equals s4\n";
else
output += "s3 does not equal s4\n";
// test compareTo
output += "\ns1.compareTo( s2
"\ns2.compareTo( s1 ) is "
"\ns1.compareTo( s1 ) is "
"\ns3.compareTo( s4 ) is "
"\ns4.compareTo( s3 ) is "

)
+
+
+
+

Outline

Test two objects for


equality, but ignore case
of letters in Strings

is " + s1.compareTo( s2 ) +
s2.compareTo( s1 ) +
s1.compareTo( s1 ) +
s3.compareTo( s4 ) +
s4.compareTo( s3 ) + "\n\n";

StringCompare.j
ava
Line 30
Method compareTo
compares String objects
Lines 36-40
Line 43 and 49

Method regionMatches
// test regionMatches (case sensitive)
if ( s3.regionMatches( 0, s4, 0, 5 ) )
compares portions of two
output += "First 5 characters of s3 and s4 match\n";
String objects for equality
else
output += "First 5 characters of s3 and s4 do not match\n";
// test regionMatches (ignore case)
if ( s3.regionMatches( true, 0, s4, 0, 5 ) )
output += "First 5 characters of s3 and s4 match";
else
output += "First 5 characters of s3 and s4 do not match";

2003 Prentice Hall, Inc.


All rights reserved.

53
54
55
56
57
58
59
60

JOptionPane.showMessageDialog( null, output,


"String comparisons", JOptionPane.INFORMATION_MESSAGE );

Outline
StringCompare.j
ava

System.exit( 0 );
}
} // end class StringCompare

2003 Prentice Hall, Inc.


All rights reserved.

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. 11.4: StringStartEnd.java


// String methods startsWith and endsWith.
import javax.swing.*;

StringStartEnd.
java

public class StringStartEnd {


public static void main( String args[] )
{
String strings[] = { "started", "starting", "ended", "ending" };
String output = "";

Line 15
Line 24

// test method startsWith


for ( int count = 0; count < strings.length; count++ )
if ( strings[ count ].startsWith( "st" ) )
output += "\"" + strings[ count ] + "\" starts with \"st\"\n";
output += "\n";
// test method startsWith starting from position
// 2 of the string
for ( int count = 0; count < strings.length; count++ )

Method startsWith
determines if String starts
with specified characters

if ( strings[ count ].startsWith( "art", 2 ) )


output += "\"" + strings[ count ] +
"\" starts with \"art\" at position 2\n";

2003 Prentice Hall, Inc.


All rights reserved.

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

Outline

output += "\n";
// test method endsWith
for ( int count = 0; count < strings.length; count++ )

StringStartEnd.
java

if ( strings[ count ].endsWith( "ed" ) )


output += "\"" + strings[ count ] + "\" ends with \"ed\"\n";

Line 33

Method endsWith
String ends
with specified characters

JOptionPane.showMessageDialog( null, output,


determines
"String Class Comparisons", JOptionPane.INFORMATION_MESSAGE
);if
System.exit( 0 );
}
} // end class StringStartEnd

2003 Prentice Hall, Inc.


All rights reserved.

11.3.4 Locating Characters and Substrings


in Strings
Search for characters in String

Method indexOf
Method lastIndexOf

2003 Prentice Hall, Inc. All rights reserved.

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

Outline

// Fig. 11.5: StringIndexMethods.java


// String searching methods indexOf and lastIndexOf.
import javax.swing.*;

StringIndexMeth
ods.java

public class StringIndexMethods {


public static void main( String args[] )
{
String letters = "abcdefghijklmabcdefghijklm";

Lines 12-16
Lines 19-26

// test indexOf to locate a character in a string


Method
String output = "'c' is located at index " + letters.indexOf( 'c'
);

indexOf finds first


occurrence of character in String

output += "\n'a' is located at index " + letters.indexOf( 'a', 1 );


output += "\n'$' is located at index " + letters.indexOf( '$' );
// test lastIndexOf to find a character in a string
output += "\n\nLast 'c' is located at index " +
letters.lastIndexOf( 'c' );
output += "\nLast 'a' is located at index " +
letters.lastIndexOf( 'a', 25 );
output += "\nLast '$' is located at index " +
letters.lastIndexOf( '$' );

Method lastIndexOf
finds last occurrence of
character in String

2003 Prentice Hall, Inc.


All rights reserved.

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

Outline

// test indexOf to locate a substring in a string


output += "\n\n\"def\" is located at index " +
letters.indexOf( "def" );

StringIndexMeth
ods.java

output += "\n\"def\" is located at index " +


letters.indexOf( "def", 7 );
output += "\n\"hello\" is located at index " +
letters.indexOf( "hello" );
// test lastIndexOf to find a substring in a string
output += "\n\nLast \"def\" is located at index " +
letters.lastIndexOf( "def" );

Lines 29-46
Methods indexOf and
lastIndexOf can also find
occurrences of substrings

output += "\nLast \"def\" is located at index " +


letters.lastIndexOf( "def", 25 );
output += "\nLast \"hello\" is located at index " +
letters.lastIndexOf( "hello" );
JOptionPane.showMessageDialog( null, output,
"String searching methods", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}

// end class StringIndexMethods

2003 Prentice Hall, Inc.


All rights reserved.

Outline

StringIndexMeth
ods.java

2003 Prentice Hall, Inc.


All rights reserved.

11.3.5 Extracting Substrings from Strings


Create Strings from other Strings

Method substring

2003 Prentice Hall, Inc. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

Outline

// Fig. 11.6: SubString.java


// String class substring methods.
import javax.swing.*;

SubString.java

public class SubString {

Line 13

public static void main( String args[] )


{
String letters = "abcdefghijklmabcdefghijklm";
// test substring methods
String output = "Substring from index 20 to end is " +
"\"" + letters.substring( 20 ) + "\"\n";
output += "Substring from index 3 up to 6 is " +
"\"" + letters.substring( 3, 6 ) + "\"";

Line 16
Beginning at index 20,
extract characters from
String letters
Extract characters from index 3
to 6 from String letters

JOptionPane.showMessageDialog( null, output,


"String substring methods", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
} // end class SubString

2003 Prentice Hall, Inc.


All rights reserved.

11.3.6 Concatenating Strings


Method concat

Concatenate two String objects

2003 Prentice Hall, Inc. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

Outline

// Fig. 11.7: StringConcatenation.java


// String concat method.
import javax.swing.*;

StringConcatena
tion.java

public class StringConcatenation {


public static void main( String args[] )
{
String s1 = new String( "Happy " );
String s2 = new String( "Birthday" );

Line 14
Concatenate String s2
Line 15
to String s1

String output = "s1 = " + s1 + "\ns2 = " + s2;


output += "\n\nResult of s1.concat( s2 ) = " + s1.concat( s2 );
output += "\ns1 after concatenation = " + s1;

However, String s1 is not


modified by method concat

JOptionPane.showMessageDialog( null, output,


"String method concat", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
} // end class StringConcatenation

2003 Prentice Hall, Inc.


All rights reserved.

11.3.7 Miscellaneous String Methods


Miscellaneous String methods

Return modified copies of String


Return character array

2003 Prentice Hall, Inc. All rights reserved.

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

Outline

// Fig. 11.8: StringMiscellaneous2.java


// String methods replace, toLowerCase, toUpperCase, trim and toCharArray.
import javax.swing.*;

StringMiscellan
eous2.java

public class StringMiscellaneous2 {


public static void
{
String s1 = new
String s2 = new
String s3 = new

main( String args[] )


String( "hello" );
String( "GOODBYE" );
String( "
spaces
" );

Line 17
Use method replace to return s1
copy in which every occurrence of
Line 20
l is replaced with L
Line 21 to
toUpperCase
return s1 copy in which every
Line 24
character is uppercase

String output = "s1 = " + s1 + "\ns2 = " + s2 + "\ns3 = "Use


+ s3;
method
// test method replace
output += "\n\nReplace 'l' with 'L' in s1: " +
s1.replace( 'l', 'L' );
// test toLowerCase and toUpperCase
output += "\n\ns1.toUpperCase() = " + s1.toUpperCase()
"\ns2.toLowerCase() = " + s2.toLowerCase();
// test trim method
output += "\n\ns3 after trim = \"" + s3.trim() + "\"";

Use method toLowerCase to


return s2 copy in which every
character is uppercase
+
Use method trim to
return s3 copy in which
whitespace is eliminated

2003 Prentice Hall, Inc.


All rights reserved.

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

// test toCharArray method


char charArray[] = s1.toCharArray();
output += "\n\ns1 as a character array = ";

Use method toCharArray to


return character array of s1

Outline

StringMiscellan
eous2.java

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


output += charArray[ count ];

Line 27

JOptionPane.showMessageDialog( null, output,


"Additional String methods", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
} // end class StringMiscellaneous2

2003 Prentice Hall, Inc.


All rights reserved.

11.3.8 String Method valueOf


String provides static class methods
Method valueOf

Returns String representation of object, data, etc.

2003 Prentice Hall, Inc. All rights reserved.

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. 11.9: StringValueOf.java


// String valueOf methods.
import javax.swing.*;

StringValueOf.j
ava

public class StringValueOf {


public static void main( String args[] )
{
char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
boolean booleanValue = true;
char characterValue = 'Z';
int integerValue = 7;
long longValue = 10000000L;
float floatValue = 2.5f; // f suffix indicates that 2.5 is a float
double doubleValue = 33.333;
Object objectRef = "hello"; // assign string to an Object reference

Lines 20-26

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


"\npart of char array = " + String.valueOf( charArray, 3, 3 ) +
"\nboolean = " + String.valueOf( booleanValue ) +
"\nchar = " + String.valueOf( characterValue ) +
static method valueOf of
"\nint = " + String.valueOf( integerValue ) +
class String returns String
"\nlong = " + String.valueOf( longValue ) +
"\nfloat = " + String.valueOf( floatValue ) +
representation of various types
"\ndouble = " + String.valueOf( doubleValue ) +
"\nObject = " + String.valueOf( objectRef );

2003 Prentice Hall, Inc.


All rights reserved.

27
28
29
30
31
32
33
34

JOptionPane.showMessageDialog( null, output,


"String valueOf methods", JOptionPane.INFORMATION_MESSAGE );

Outline
StringValueOf.j
ava

System.exit( 0 );
}
} // end class StringValueOf

2003 Prentice Hall, Inc.


All rights reserved.

11.4 Class StringBuffer


Class StringBuffer
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

2003 Prentice Hall, Inc. All rights reserved.

11.4.1 StringBuffer Constructors


Three StringBuffer constructors
Default creates StringBuffer with no characters

Capacity of 16 characters

2003 Prentice Hall, Inc. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

Outline

// Fig. 11.10: StringBufferConstructors.java


// StringBuffer constructors.
import javax.swing.*;

Default constructor creates


empty StringBuffer with
capacity of StringBufferCon
16 characters
structors.java

public class StringBufferConstructors {


public static void main( String args[] )
{
StringBuffer buffer1 = new StringBuffer();
StringBuffer buffer2 = new StringBuffer( 10 );
StringBuffer buffer3 = new StringBuffer( "hello" );

Second constructor creates empty


Line 9
StringBuffer with capacity of
specified (10) characters
Line 10

String output = "buffer1 = \"" + buffer1.toString() + "\"" +


"\nbuffer2 = \"" + buffer2.toString() + "\"" +
"\nbuffer3 = \"" + buffer3.toString() + "\"";

Third constructor creates


Line 11
StringBuffer with
String hello and
Lines 13-15
capacity of 16 characters

JOptionPane.showMessageDialog( null, output,


"StringBuffer constructors", JOptionPane.INFORMATION_MESSAGE );
Method
System.exit( 0 );
}

toString returns
String representation of
StringBuffer

} // end class StringBufferConstructors

2003 Prentice Hall, Inc.


All rights reserved.

11.4.2 StringBuffer Methods length, capacity,


setLength and ensureCapacity

Method length
Return StringBuffer length

Method capacity
Return StringBuffer capacity

Method setLength
Increase or decrease StringBuffer length

Method ensureCapacity

Set StringBuffer capacity


Guarantee that StringBuffer has minimum capacity

2003 Prentice Hall, Inc. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

Outline

// Fig. 11.11: StringBufferCapLen.java


// StringBuffer length, setLength, capacity and ensureCapacity methods.
import javax.swing.*;

StringBufferCap
Len.java

public class StringBufferCapLen {


public static void main( String args[] )
{
StringBuffer buffer = new StringBuffer( "Hello, how are you?" );
String output = "buffer = " + buffer.toString() + "\nlength = " +
buffer.length() + "\ncapacity = " + buffer.capacity();
buffer.ensureCapacity( 75 );
output += "\n\nNew capacity = " + buffer.capacity();
buffer.setLength( 10 );
output += "\n\nNew length = " + buffer.length() +
"\nbuf = " + buffer.toString();
JOptionPane.showMessageDialog( null, output,
"StringBuffer length and capacity Methods",
JOptionPane.INFORMATION_MESSAGE );

Method length
Line 12 returns
StringBuffer length
Line 12
Method capacity returns
StringBuffer
Line 14 capacity

Line 17
Use method ensureCapacity
to set capacity to 75
Use method setLength
to set length to 10

2003 Prentice Hall, Inc.


All rights reserved.

25
26
27
28

Outline

System.exit( 0 );
}
} // end class StringBufferCapLen

StringBufferCap
Len.java
Only 10 characters
from
StringBuffer are
printed

Only 10 characters from


StringBuffer are printed

2003 Prentice Hall, Inc.


All rights reserved.

11.4.3 StringBuffer Methods charAt,


setCharAt, getChars and reverse
Manipulating StringBuffer characters
Method charAt
Return StringBuffer character at specified index

Method setCharAt
Set StringBuffer character at specified index

Method getChars
Return character array from StringBuffer

Method reverse

Reverse StringBuffer contents

2003 Prentice Hall, Inc. All rights reserved.

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

Outline

// Fig. 11.12: StringBufferChars.java


// StringBuffer methods charAt, setCharAt, getChars and reverse.
import javax.swing.*;

StringBufferCha
rs.java

public class StringBufferChars {


public static void main( String args[] )
{
StringBuffer buffer = new StringBuffer( "hello there" );
String output = "buffer = " + buffer.toString() +
"\nCharacter at 0: " + buffer.charAt( 0 ) +
"\nCharacter at 4: " + buffer.charAt( 4 );
char charArray[] = new char[ buffer.length() ];
buffer.getChars( 0, buffer.length(), charArray, 0 );
output += "\n\nThe characters are: ";

Lines 12-13
Return StringBuffer
characters at indices 0
Line 16
and 4, respectively
Lines 22-23
Return character array
from StringBuffer

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


output += charArray[ count ];
buffer.setCharAt( 0, 'H' );
buffer.setCharAt( 6, 'T' );
output += "\n\nbuf = " + buffer.toString();

Replace characters at
indices 0 and 6 with H
and T, respectively

2003 Prentice Hall, Inc.


All rights reserved.

26
27
28
29
30
31
32
33
34
35
36

buffer.reverse();
output += "\n\nbuf = " + buffer.toString();
JOptionPane.showMessageDialog( null, output,
"StringBuffer character methods",
JOptionPane.INFORMATION_MESSAGE );

Outline

Reverse characters in
StringBuffer
StringBufferCha
rs.java
Lines 26

System.exit( 0 );
}
} // end class StringBufferChars

2003 Prentice Hall, Inc.


All rights reserved.

11.4.4 StringBuffer append Methods


Method append

Allow data values to be added to StringBuffer

2003 Prentice Hall, Inc. All rights reserved.

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

Outline

// Fig. 11.13: StringBufferAppend.java


// StringBuffer append methods.
import javax.swing.*;

StringBufferApp
end.java

public class StringBufferAppend {


public static void main( String args[] )
{
Object objectRef = "hello";
String string = "goodbye";
char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
boolean booleanValue = true;
char characterValue = 'Z';
int integerValue = 7;
long longValue = 10000000;
float floatValue = 2.5f; // f suffix indicates 2.5 is a float
double doubleValue = 33.333;
StringBuffer lastBuffer = new StringBuffer( "last StringBuffer" );
StringBuffer buffer = new StringBuffer();
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(

Line 21
Line 23
Line 25
Line 27

Append String hello

objectRef );
to StringBuffer
" " );
// each of these contains two spaces
string );
Append String goodbye
" " );
charArray );
Append a b c d e f
" " );
charArray, 0, 3 );

Append a b c

2003 Prentice Hall, Inc.


All rights reserved.

28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(
buffer.append(

" " );
booleanValue );
" " );
characterValue );
" " );
integerValue );
" " );
longValue );
" " );
floatValue );
" " );
doubleValue );
" " );
lastBuffer );

Outline
StringBufferApp
Append boolean, char,
int,
end.java
long, float and double
Line 29-39

JOptionPane.showMessageDialog( null,
"buffer = " + buffer.toString(), "StringBuffer append Methods",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
} // end StringBufferAppend

2003 Prentice Hall, Inc.


All rights reserved.

11.4.5 StringBuffer Insertion and Deletion


Methods
Method insert
Allow data-type values to be inserted into StringBuffer

Methods delete and deleteCharAt

Allow characters to be removed from StringBuffer

2003 Prentice Hall, Inc. All rights reserved.

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. 11.14: StringBufferInsert.java


// StringBuffer methods insert and delete.
import javax.swing.*;

StringBufferIns
ert.java

public class StringBufferInsert {


public static void main( String args[] )
{
Object objectRef = "hello";
String string = "goodbye";
char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
boolean booleanValue = true;
char characterValue = 'K';
int integerValue = 7;
long longValue = 10000000;
float floatValue = 2.5f; // f suffix indicates that 2.5 is a float
double doubleValue = 33.333;
StringBuffer buffer = new StringBuffer();
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(

0,
0,
0,
0,
0,
0,
0,

Lines 20-26

objectRef );
" " ); // each of these contains two spaces
string );
" " );
Use method insert to insert
charArray );
data in beginning of
" " );
StringBuffer
charArray, 3, 3 );

2003 Prentice Hall, Inc.


All rights reserved.

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.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(
buffer.insert(

0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,

Outline

" " );
booleanValue );
" " );
characterValue );
" " );
integerValue );
" " );
longValue );
" " );
floatValue );
" " );
doubleValue );

Use method insert to insertStringBufferIns


ert.java
data in beginning of
StringBuffer
Lines 27-38
Line 42

String output = "buffer after inserts:\n" +


buffer.deleteCharAt( 10 );
buffer.delete( 2, 6 );

Use method deleteCharAt to


Lineindex
43 10 in
remove character from
buffer.toString();
StringBuffer

// delete 5 in 2.5
// delete .333 in 33.333

output += "\n\nbuffer after deletes:\n" +

Remove characters from


buffer.toString(); indices 2 through 5 (inclusive)

JOptionPane.showMessageDialog( null, output,


"StringBuffer insert/delete", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
} // end class StringBufferInsert

2003 Prentice Hall, Inc.


All rights reserved.

Outline

StringBufferIns
ert.java

2003 Prentice Hall, Inc.


All rights reserved.

11.5 Class Character


Treat primitive variables as objects
Type wrapper classes
Boolean
Character
Double
Float
Byte
Short
Integer
Long

We examine class Character

2003 Prentice Hall, Inc. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

Outline

// Fig. 11.15: StaticCharMethods.java


// Static Character testing methods and case conversion methods.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

StaticCharMetho
ds.java

public class StaticCharMethods extends JFrame {


private char c;
private JLabel promptLabel;
private JTextField inputField;
private JTextArea outputArea;
// constructor builds GUI
public StaticCharMethods()
{
super( "Static Character Methods" );
Container container = getContentPane();
container.setLayout( new FlowLayout() );
promptLabel = new JLabel( "Enter a character and press Enter" );
container.add( promptLabel );
inputField = new JTextField( 5 );

2003 Prentice Hall, Inc.


All rights reserved.

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

Outline

inputField.addActionListener(
new ActionListener() {

// anonymous inner class

StaticCharMetho
ds.java

// handle textfield event


public void actionPerformed( ActionEvent event )
{
String s = event.getActionCommand();
c = s.charAt( 0 );
buildOutput();
}
} // end anonymous inner class
); // end call to addActionListener
container.add( inputField );
outputArea = new JTextArea( 10, 20 );
container.add( outputArea );
setSize( 300, 220 );
setVisible( true );

// set the window size


// show the window

} // end constructor

2003 Prentice Hall, Inc.


All rights reserved.

50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74

Outline

// display character info in outputArea


private void buildOutput()
{
outputArea.setText( "is defined: " + Character.isDefined(Determine
c ) +
whetherStaticCharMetho
c is
"\nis digit: " + Character.isDigit( c ) +
defined Unicode digit
ds.java
"\nis first character in a Java identifier: " +
Character.isJavaIdentifierStart( c ) +
Determine whetherLine
c can
54 be used
"\nis part of a Java identifier: " +
as first character in identifier
Character.isJavaIdentifierPart( c ) +
"\nis letter: " + Character.isLetter( c ) +
Line 56
"\nis letter or digit: " + Character.isLetterOrDigit( c ) + Determine whether c can be
"\nis lower case: " + Character.isLowerCase( c ) +
used as identifier
character
Line 58
"\nis upper case: " + Character.isUpperCase( c ) +
"\nto upper case: " + Character.toUpperCase( c ) +
Determine whether c is a letter
"\nto lower case: " + Character.toLowerCase( c ) );
Line 59
}
// create StaticCharMethods object to begin execution
public static void main( String args[] )
{
StaticCharMethods application = new StaticCharMethods();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}

Determine whether
Line
60 or digit
c is
letter

Lines
61-62c is
Determine
whether
uppercase or lowercase

} // end class StaticCharMethods

2003 Prentice Hall, Inc.


All rights reserved.

Outline

StaticCharMetho
ds.java

2003 Prentice Hall, Inc.


All rights reserved.

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

Outline

// Fig. 11.15: StaticCharMethods2.java


// Static Character conversion methods.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

StaticCharMetho
ds2.java

public class StaticCharMethods2 extends JFrame {


private char c;
private int digit, radix;
private JLabel prompt1, prompt2;
private JTextField input, radixField;
private JButton toChar, toInt;
// constructor builds GUI
public StaticCharMethods2()
{
super( "Character Conversion Methods" );
Container container = getContentPane();
container.setLayout( new FlowLayout() );
prompt1 = new JLabel( "Enter a digit or character " );
input = new JTextField( 5 );
container.add( prompt1 );
container.add( input );

2003 Prentice Hall, Inc.


All rights reserved.

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

Outline

prompt2 = new JLabel( "Enter a radix " );


radixField = new JTextField( 5 );
container.add( prompt2 );
container.add( radixField );

StaticCharMetho
ds2.java

toChar = new JButton( "Convert digit to character" );


toChar.addActionListener(

Line 44

new ActionListener() { // anonymous inner class


// handle toChar JButton event
public void actionPerformed( ActionEvent actionEvent )
{
digit = Integer.parseInt( input.getText() );
radix = Integer.parseInt( radixField.getText() );
JOptionPane.showMessageDialog( null,
"Convert digit to character: " +
Character.forDigit( digit, radix ) );
}
} // end anonymous inner class
); // end call to addActionListener

Use method forDigit to convert


int digit to number-system
character specified by int radix

2003 Prentice Hall, Inc.


All rights reserved.

51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75

Outline

toInt = new JButton( "Convert character to digit" );


toInt.addActionListener(
new ActionListener() {

// anonymous inner class

// handle toInt JButton event


public void actionPerformed( ActionEvent actionEvent )
{
String s = input.getText();
c = s.charAt( 0 );
radix = Integer.parseInt( radixField.getText() );
JOptionPane.showMessageDialog( null,
"Convert character to digit: " +
Character.digit( c, radix ) );
}

StaticCharMetho
ds2.java

} // end anonymous inner class


); // end call to addActionListener

Line 64

Use method digit to convert


char c to number-system
integer specified by int radix

container.add( toChar );
container.add( toInt );
setSize( 275, 150 ); // set the window size
setVisible( true );
// show the window
}

2003 Prentice Hall, Inc.


All rights reserved.

76
77
78
79
80
81
82
83
84

// create StaticCharMethods2 object execute application


public static void main( String args[] )
{
StaticCharMethods2 application = new StaticCharMethods2();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}

Outline
StaticCharMetho
ds2.java

} // end class StaticCharMethods2

2003 Prentice Hall, Inc.


All rights reserved.

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

Outline

// Fig. 11.17: OtherCharMethods.java


// Non-static Character methods.
import javax.swing.*;

OtherCharMethod
s.java

public class OtherCharMethods {


public static void main( String args[] )
{
Character c1 = new Character( 'A' );
Character c2 = new Character( 'a' );
String output = "c1 = " + c1.charValue() +
"\nc2 = " + c2.toString();

Lines 12-15
Characters non-static methods
charValue, toString and equals

if ( c1.equals( c2 ) )
output += "\n\nc1 and c2 are equal";
else
output += "\n\nc1 and c2 are not equal";
JOptionPane.showMessageDialog( null, output,
"Non-static Character methods",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
} // end class OtherCharMethods

2003 Prentice Hall, Inc.


All rights reserved.

11.6 Class StringTokenizer


Tokenizer

Partition String into individual substrings


Use delimiter
Java offers java.util.StringTokenizer

2003 Prentice Hall, Inc. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

Outline

// Fig. 11.18: TokenTest.java


// StringTokenizer class.
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

TokenTest.java
Line 24

public class TokenTest extends JFrame {


private JLabel promptLabel;
private JTextField inputField;
private JTextArea outputArea;
// set up GUI and event handling
public TokenTest()
{
super( "Testing Class StringTokenizer" );
Container container = getContentPane();
container.setLayout( new FlowLayout() );
promptLabel = new JLabel( "Enter a sentence and press Enter" );
container.add( promptLabel );
inputField = new JTextField( 20 );

inputField contains String to


be parsed by StringTokenizer

2003 Prentice Hall, Inc.


All rights reserved.

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

Outline

inputField.addActionListener(
new ActionListener() {

// anonymous inner class

Use StringTokenizer to parse


String
TokenTest.java
using default delimiter \n\t\r

// handle text field event


public void actionPerformed( ActionEvent event )
{
StringTokenizer tokens =
new StringTokenizer( event.getActionCommand() );

Line 33
Line
Count number
of36
tokens

outputArea.setText( "Number of elements: " +


tokens.countTokens() + "\nThe tokens are:\n" );

Lines 38-39

while ( tokens.hasMoreTokens() )
outputArea.append( tokens.nextToken() + "\n" );
}
} // end anonymous inner class

Append next token to outputArea,


as long as tokens exist

); // end call to addActionListener


container.add( inputField );
outputArea = new JTextArea( 10, 20 );
outputArea.setEditable( false );
container.add( new JScrollPane( outputArea ) );
setSize( 275, 240 ); // set the window size
setVisible( true );
// show the window
}

2003 Prentice Hall, Inc.


All rights reserved.

54
55
56
57
58
59
60
61
62

// execute application
public static void main( String args[] )
{
TokenTest application = new TokenTest();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}

Outline
TokenTest.java

} // end class TokenTest

2003 Prentice Hall, Inc.


All rights reserved.

11.7 Card Shuffling and Dealing Simulation


Develop DeckOfCards 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

2003 Prentice Hall, Inc. All rights reserved.

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

Outline

// Fig. 11.19: DeckOfCards.java


// Card shuffling and dealing program.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

DeckOfCards.jav
a

public class DeckOfCards extends JFrame {


private Card deck[];
private int currentCard;
private JButton dealButton, shuffleButton;
private JTextField displayField;
private JLabel statusLabel;
// set up deck of cards and GUI
public DeckOfCards()
{
super( "Card Dealing Program" );

Lines 19 and 29
Line 30

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 ];
currentCard = -1;

Most recently dealt Cards in deck array


(-1 if no Cards have been dealt)

2003 Prentice Hall, Inc.


All rights reserved.

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

// populate deck with Card objects


for ( int count = 0; count < deck.length; count++ )
deck[ count ] = new Card( faces[ count % 13 ],
suits[ count / 13 ] );
// set up GUI and event handling
Container container = getContentPane();
container.setLayout( new FlowLayout() );
dealButton = new JButton( "Deal card" );
dealButton.addActionListener(
new ActionListener() {

// anonymous inner

Outline
Fill deck array with Cards
DeckOfCards.jav
a
Lines 27-29
Line 43

When user presses Deal Card


Line 46
class button, method dealCard
gets next card in deck array

// deal one card


public void actionPerformed( ActionEvent actionEvent )
{
Card dealt = dealCard();

Display Card in JTextField

if ( dealt != null ) {
displayField.setText( dealt.toString() );
statusLabel.setText( "Card #: " + currentCard );
}
else {
displayField.setText( "NO MORE CARDS TO DEAL" );
statusLabel.setText( "Shuffle cards to continue" );
}

2003 Prentice Hall, Inc.


All rights reserved.

54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78

Outline

} // end anonymous inner class


); // end call to addActionListener

DeckOfCards.jav
a

container.add( dealButton );

Line 70

shuffleButton = new JButton( "Shuffle cards" );


shuffleButton.addActionListener(
new ActionListener() {

// anonymous inner class

// shuffle deck
public void actionPerformed( ActionEvent actionEvent )
{
displayField.setText( "SHUFFLING ..." );
shuffle();
displayField.setText( "DECK IS SHUFFLED" );
}

When user presses Shuffle


Cards button, method
shuffle shuffles cards

} // end anonymous inner class


); // end call to addActionListener
container.add( shuffleButton );

2003 Prentice Hall, Inc.


All rights reserved.

79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103

Outline

displayField = new JTextField( 20 );


displayField.setEditable( false );
container.add( displayField );

DeckOfCards.jav
a

statusLabel = new JLabel();


container.add( statusLabel );
setSize( 275, 120 );
setVisible( true );

Lines 92-102

// set window size


// show window

}
// shuffle deck of cards with one-pass algorithm
private void shuffle()
{
currentCard = -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;
}

Shuffle cards by swapping


each Card with randomly
selected Card

2003 Prentice Hall, Inc.


All rights reserved.

Outline

104
dealButton.setEnabled( true );
105
}
106
107
// deal one card
DeckOfCards.jav
108
private Card dealCard()
If deck is not empty, a Card
a
109
{
object reference is returned;
110
if ( ++currentCard < deck.length )
otherwise, null is returnedLines 108-116
111
return deck[ currentCard ];
112
else {
113
dealButton.setEnabled( false );
Lines 114 and 123
Method setEnabled enables
114
return null;
and disables JButton
115
}
116
}
117
118
// execute application
119
public static void main( String args[] )
120
{
121
DeckOfCards application = new DeckOfCards();
122
123
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
124
}
125
126 } // end class DeckOfCards
127

2003 Prentice Hall, Inc.


All rights reserved.

Outline

128 // class to represent a card


129 class Card {
Store face name and suit for
130
private String face;
specific Card, respectively
131
private String suit;
132
133
// constructor to initialize a card
134
public Card( String cardFace, String cardSuit )
135
{
136
face = cardFace;
137
suit = cardSuit;
138
}
139
140
// return String represenation of Card
141
public String toString()
142
{
143
return face + " of " + suit;
144
}
145
146 } // end class Card

DeckOfCards.jav
a

Lines 130-131

2003 Prentice Hall, Inc.


All rights reserved.

11.8 Regular Expressions, Class Pattern


and Class Matcher
Regular expression
Sequence of characters and symbols
Define set of strings

Class Pattern
An immutable regular expression

Class Match

A regular expression matching operation

2003 Prentice Hall, Inc. All rights reserved.

11.8 Regular Expressions, Class Pattern


and Class Matcher

Character
\d

Matches

Matches

any digit

Character
\D

\w

any word character

\W

any non-word character

\s

any whitespace

\S

any non-whitespace

Fig. 11.20 Predefined character classes.

2003 Prentice Hall, Inc. All rights reserved.

any non-digit

11.8 Regular Expressions, Class Pattern


and Class Matcher

Quantifier

Matches

Matches zero or more occurrences of the pattern.

Matches one or more occurrences of the pattern.

Matches zero or one occurrences of the pattern.

{n}

Matches exactly n occurrences.

{n,}

Matches at least n occurrences.

{n,m}

Matches between n and m (inclusive) occurrences.

Fig. 11.22 Quantifiers used regular expressions.

2003 Prentice Hall, Inc. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

Outline

// Fig. 11.21: ValidateFrame.java


// Validate user information using regular expressions.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

ValidateFrame.j
ava

public class ValidateFrame extends JFrame {


private JTextField phoneTextField, zipTextField, stateTextField,
cityTextField, addressTextField, firstTextField, lastTextField;
public ValidateFrame()
{
super( "Validate" );
// create the GUI components
JLabel phoneLabel = new JLabel( "Phone" );
JLabel zipLabel = new JLabel( "Zip" );
JLabel stateLabel = new JLabel( "State" );
JLabel cityLabel = new JLabel( "City" );
JLabel addressLabel = new JLabel( "Address" );
JLabel firstLabel = new JLabel( "First Name" );
JLabel lastLabel = new JLabel( "Last Name" );
JButton okButton = new JButton( "OK" );

2003 Prentice Hall, Inc.


All rights reserved.

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

Outline

okButton.addActionListener(
new ActionListener() { // inner class

ValidateFrame.j
ava

public void actionPerformed( ActionEvent event ) {


validateDate();
}
} // end inner class
); // end call to addActionListener
phoneTextField = new JTextField( 15 );
zipTextField = new JTextField( 5 );
stateTextField = new JTextField( 2 );
cityTextField = new JTextField( 12 );
addressTextField = new JTextField( 20 );
firstTextField = new JTextField( 20 );
lastTextField = new JTextField( 20 );
JPanel firstName = new JPanel();
firstName.add( firstLabel );
firstName.add( firstTextField );
JPanel lastName = new JPanel();
lastName.add( lastLabel );
lastName.add( lastTextField );

2003 Prentice Hall, Inc.


All rights reserved.

52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75

JPanel address1 = new JPanel();


address1.add( addressLabel );
address1.add( addressTextField );

Outline

JPanel address2 = new JPanel();


address2.add( cityLabel );
address2.add( cityTextField );
address2.add( stateLabel );
address2.add( stateTextField );
address2.add( zipLabel );
address2.add( zipTextField );

ValidateFrame.j
ava

JPanel phone = new JPanel();


phone.add( phoneLabel );
phone.add( phoneTextField );
JPanel ok = new JPanel();
ok.add( okButton );
// add the components to the application
Container container = getContentPane();
container.setLayout( new GridLayout( 6, 1 ) );

2003 Prentice Hall, Inc.


All rights reserved.

76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94

container.add(
container.add(
container.add(
container.add(
container.add(
container.add(

Outline

firstName );
lastName );
address1 );
address2 );
phone );
ok );

ValidateFrame.j
ava

setSize( 325, 225 );


setVisible( true );
} // end ValidateFrame constructor
public static void main( String args[] )
{
ValidateFrame application = new ValidateFrame();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
// handles okButton action event

2003 Prentice Hall, Inc.


All rights reserved.

95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120

Outline

private void validateDate()


{
// ensure that no textboxes are empty
if ( lastTextField.getText().equals( "" ) ||
firstTextField.getText().equals( "" ) ||
addressTextField.getText().equals( "" ) ||
cityTextField.getText().equals( "" ) ||
stateTextField.getText().equals( "" ) ||
zipTextField.getText().equals( "" ) ||
phoneTextField.getText().equals( "" ) ) // end condition

ValidateFrame.j
ava
Lines 109-118

JOptionPane.showMessageDialog( this, "Please fill all fields" );


// if first name format invalid show message
else if ( !firstTextField.getText().matches( "[A-Z][a-zA-Z]*" ) )
JOptionPane.showMessageDialog( this, "Invalid first name" );

Matches returns true if the


the regular

// if last name format invalid show message


String
else if ( !lastTextField.getText().matches( "[A-Z][a-zA-Z]*"
) ) matches
expression
JOptionPane.showMessageDialog( this, "Invalid last name"
);
// if address format invalid show message
else if ( !addressTextField.getText().matches(
"\\d+\\s+([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)" ) )
JOptionPane.showMessageDialog( this, "Invalid address" );

2003 Prentice Hall, Inc.


All rights reserved.

Outline

121
// if city format invalid show message
122
else if ( !cityTextField.getText().matches(
123
"([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)" ) )
124
JOptionPane.showMessageDialog( this, "Invalid city" );
ValidateFrame.j
125
ava
126
// if state format invalid show message
127
else if ( !stateTextField.getText().matches(
Lines 122-137
128
"([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)" ) )
Matches returns true if the
129
JOptionPane.showMessageDialog( this, "Invalid state" );
130
String matches the regular
131
// if zip code format invalid show message
expression
132
else if ( !zipTextField.getText().matches( "\\d{5}" ) )
133
JOptionPane.showMessageDialog( this, "Invalid zip code" );
134
135
// if phone number format invalid show message
136
else if ( !phoneTextField.getText().matches(
137
"[1-9]\\d{2}-[1-9]\\d{2}-\\d{4}" ) )
138
JOptionPane.showMessageDialog( this, "Invalid phone number" );
139
140
else // information is valid, signal user
141
JOptionPane.showMessageDialog( this, "Thank you" );
142
143
} // end method validateDate
144
145 } // end class ValidateFrame

2003 Prentice Hall, Inc.


All rights reserved.

Outline
ValidateFrame.j
ava
Error message if
TextBox left blank

Signal that the Zip TextBox


was entered improperly

Signify that all the TextBoxes


were entered in correct format

2003 Prentice Hall, Inc.


All rights reserved.

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. 11.23: RegexSubstitution.java


// Using methods replaceFirst, replaceAll and split.
import javax.swing.*;

RegexSubstituti

public class RegexSubstitution


on.java
{
public static void main( String args[] )
Line 15
{
Replace every instance of *
String firstString = "This sentence ends in 5 stars *****";
String secondString = "1, 2, 3, 4, 5, 6, 7, 8"; in firstString with ^

Line 20

String output = "Original String 1: " + firstString;


// replace '*' with '^'
firstString = firstString.replaceAll( "\\*", "^"

Line 26
Replace every instance of stars
in firstString with carets
);

output += "\n^ substituted for *: " + firstString;


// replace 'stars' with 'carets'
Replace every word
firstString = firstString.replaceAll( "stars", "carets" );

in
firstString with word

output += "\n\"carets\" substituted for \"stars\": " + firstString;


// replace words with 'word'
output += "\nEvery word replaced by \"word\": " +
firstString.replaceAll( "\\w+", "word" );

2003 Prentice Hall, Inc.


All rights reserved.

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

output += "\n\nOriginal String 2: " + secondString;

Outline

replaceFirst replaces a single


// replace first three digits with 'digit'
RegexSubstituti
occurrence of the regular expression
for ( int i = 0; i < 3; i++ )
on.java
secondString = secondString.replaceFirst( "\\d", "digit" );
Line 32

output += "\nFirst 3 digits replaced by \"digit\" : " +


secondString;
output += "\nString split at commas: [";

Line 38

String[] results = secondString.split( ",\\s*" ); // split on commas


for ( int i = 0; i < results.length; i++ ) split returns array of substrings between
output += "\"" + results[ i ] + "\", "; //
outputofresults
matches
the regular expression
// remove the extra comma and add a bracket
output = output.substring( 0, output.length() - 2 ) + "]";
JOptionPane.showMessageDialog( null, output );
System.exit( 0 );
} // end method main
} // end class RegexSubstitution

2003 Prentice Hall, Inc.


All rights reserved.

Outline

RegexSubstituti
on.java

2003 Prentice Hall, Inc.


All rights reserved.

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

Outline

// Fig. 11.24: RegexMatches.java


// Demonstrating Classes Pattern and Matcher.
import java.util.regex.*;
import javax.swing.*;
class RegexMatches
{
public static void main( String args[] )
{
String output = "";

RegexMatches.ja
va
Lines 13-14
compile creates an immutable
Line 22
regular expression object

// create regular expression


Pattern expression =
Pattern.compile( "J.*\\d[0-35-9]-\\d\\d-\\d\\d" );
String string1 = "Jane's Birthday is 05-12-75\n" +
"Dave's Birthday is 11-04-68\n" +
matcher associates
"John's Birthday is 04-28-73\n" +
object with a string
"Joe's Birthday is 12-17-77";

Line 24
Line 25
a Pattern

// match regular expression to string and print matches


Matcher matcher = expression.matcher( string1 );
while ( matcher.find() )
output += matcher.group() + "\n";

find gets the first substring that


matches the regular expression
group returns the
matched substring

2003 Prentice Hall, Inc.


All rights reserved.

26
27
28
29
30
31
32

JOptionPane.showMessageDialog( null, output );


System.exit( 0 );

Outline
RegexMatches.ja
va

} // end main
} // end class RegexMatches

2003 Prentice Hall, Inc.


All rights reserved.

11.9 (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

2003 Prentice Hall, Inc. All rights reserved.

11.9 (Optional Case Study) Thinking About


Objects: Event Handling
Event
Message that notifies an object of an action
Action: Elevator arrives at Floor
Consequence: Elevator sends elevatorArrived event
to Elevators Door
i.e., Door is notified that Elevator has arrived
Action: Elevators Door opens
Consequence: Door sends doorOpened event to Person
i.e., Person is notified that Door has opened

Preferred naming structure

Noun (elevator) preceded by verb (arrived)

2003 Prentice Hall, Inc. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

Outline

// ElevatorSimulationEvent.java
// Basic event packet holding Location object
package com.deitel.jhtp5.elevator.event;

ElevatorSimulat
ionEvent.java

// Deitel packages
import com.deitel.jhtp5.elevator.model.*;
public class ElevatorSimulationEvent {

Represents an event
in elevator simulation

// Location that generated ElevatorSimulationEvent


private Location location;
// source of generated ElevatorSimulationEvent
private Object source;
// ElevatorSimulationEvent constructor sets Location
public ElevatorSimulationEvent( Object source,
Location location )
{
setSource( source );
setLocation( location );
}

Line 8

Line 11
Location object reference
represents location where even
was generated Line 14
Object object reference represents
object that generated event

2003 Prentice Hall, Inc.


All rights reserved.

24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

Outline

// set ElevatorSimulationEvent Location


public void setLocation( Location eventLocation )
{
location = eventLocation;
}

ElevatorSimulat
ionEvent.java

// get ElevatorSimulationEvent Location


public Location getLocation()
{
return location;
}
// set ElevatorSimulationEvent source
private void setSource( Object eventSource )
{
source = eventSource;
}
// get ElevatorSimulationEvent source
public Object getSource()
{
return source;
}
}

2003 Prentice Hall, Inc.


All rights reserved.

11.9 (Optional Case Study) Thinking About


Objects: Event Handling
Objects send ElevatorSimulationEvent
This may become confusing
Door sends ElevatorSimulationEvent to Person
upon opening
Elevator sends ElevatorSimulationEvent to Door
upon arrival

Solution:

Create several ElevatorSimulationEvent subclasses


Each subclass better represents action
e.g., BellEvent when Bell rings

2003 Prentice Hall, Inc. All rights reserved.

Fig. 11.26 Class diagram that models the generalization between


ElevatorSimulationEvent and its subclasses.

ElevatorSimulationEvent

BellEvent

DoorEvent

LightEvent

PersonMoveEvent

2003 Prentice Hall, Inc. All rights reserved.

ButtonEvent

ElevatorMoveEvent

Fig. 11.27 Triggering actions of the


ElevatorSimulationEvent subclass events
Event
BellEvent

Sent when (triggering action)


the Bell has rung

Sent by object of class


Bell

ButtonEvent

a Button has been pressed


a Button has been reset
a Door has opened
a Door has closed
a Light has turned on
a Light has turned off
a Person has been created
a Person has arrived at the Elevator
a Person has entered the Elevator
a Person has exited the Elevator
a Person has pressed a Button
a Person has exited the simulation
the Elevator has arrived at a Floor
the Elevator has departed from a Floor

Button
Button
Door
Door
Light

DoorEvent
LightEvent
PersonMoveEvent

ElevatorMoveEvent

Person

Elevator

Fig. 11.27 Triggering actions of the ElevatorSimulationEvent subclass events.

2003 Prentice Hall, Inc. All rights reserved.

11.9 (Optional Case Study) Thinking About


Objects: Event Handling
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

2003 Prentice Hall, Inc. All rights reserved.

11.9 (Optional Case Study) Thinking About


Objects: Event Handling
Modify collaboration diagram of Fig. 7.19
Incorporate event handling (Fig. 11.28)
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

2003 Prentice Hall, Inc. All rights reserved.

Fig. 11.28 Modified collaboration diagram for passengers entering


and exiting the Elevator on the first Floor
3.2.1 doorOpened( DoorEvent )

3.2 : openDoor( )

firstFloorDoor : Door
4.1.1 : resetButton( )

firstFloorButton : Button

4.2.1 : turnOnLight( )

: ElevatorShaft

4.1 :
elevatorArrived( Elevato
rMoveEvent )

firstFloorLight: Light

4.2 : elevatorArrived( ElevatorMoveEvent )


4 : elevatorArrived( ElevatorMoveEvent )

waitingPassenger : Person

ridingPassenger : Person

: Elevator
ev
at
1
e :
or leva
M to
o v rA
e E rr
ve ive
nt d(
) El

1.1: resetButton( )

2003 Prentice Hall, Inc. All rights reserved.

3.3.1 : exitElevator( )

a
ev
El
d(
ve )
rri n t
rA e
t o Ev
:
3 leva ove
e rM
to

elevatorButton: Button

2:
elevatorArrived( Elevato
rMoveEvent )

3.2.1.1 : enterElevator( )

: Bell

2.1: ringBell( )

3.3 : doorOpened( )

: ElevatorDoor

3.1: openDoor( Location )

11.9 (Optional Case Study) Thinking About


Objects: Event Handling
Event listeners
Elevator sends ElevatorMoveEvent
All event classes (in our simulation) have this structure

Door must implement interface that listens for this event


Door implements interface ElevatorMoveListener

Method elevatorArrived
Invoked when Elevator arrives
Method elevatorDeparted
Invoked when Elevator departs

2003 Prentice Hall, Inc. All rights reserved.

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

Outline

// ElevatorMoveEvent.java
// Indicates on which Floor the Elevator arrived or departed
package com.deitel.jhtp5.elevator.event;

ElevatorMoveEve
nt.java

// Deitel package
import com.deitel.jhtp5.elevator.model.*;
public class ElevatorMoveEvent extends ElevatorSimulationEvent {
// ElevatorMoveEvent constructor
public ElevatorMoveEvent( Object source, Location location )
{
super( source, location );
}
}

2003 Prentice Hall, Inc.


All rights reserved.

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

Outline

// ElevatorMoveListener.java
// Methods invoked when Elevator has either departed or arrived
package com.deitel.jhtp5.elevator.event;

ElevatorMoveLis
tener.java

public interface ElevatorMoveListener {


// invoked when Elevator has departed
public void elevatorDeparted( ElevatorMoveEvent moveEvent );
// invoked when Elevator has arrived
public void elevatorArrived( ElevatorMoveEvent moveEvent );
}

2003 Prentice Hall, Inc.


All rights reserved.

11.9 (Optional Case Study) Thinking About


Objects: Event Handling
Class diagram revisited
Modify class diagram of Fig. 10.28 to include

Signals (events)
e.g., Elevator signals arrival to Light
Self associations
e.g., Light turns itself on and off

2003 Prentice Hall, Inc. All rights reserved.

Fig. 11.31 Class diagram of our simulator


(including event handling)
1

Door
1

Signalsar
rival

Turns
on/off

Light

Resets
1

Signals
arrival

Opens /
Closes

Signals arrival

ElevatorShaft

Button

Presses
1

Informs of
opening

Person
1

Opens/Closes
1

1
1

Elevator

ElevatorDoor
Signals
arrival

1
1
1

Signals
arrival

Rings

Signals to
move

Bell

2003 Prentice Hall, Inc. All rights reserved.

1
1

Occupies

Signals
arrival

Location

Floor

You might also like