Java - profthinh ď jhtp5_11 tài liệu, giáo án, bài giảng , luận văn, luận án, đồ án, bài tập lớn về tất cả các lĩnh vực...
1 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 'y' 10 11 12 13 14 15 16 17 18 19 20 21 22 // Fig 11.1: StringConstructors.java // String class constructors import javax.swing.*; public class StringConstructors { Outline String defaultStringConstruct constructor instantiates empty ors.java string public static void main( String args[] ) Constructor { char charArray[] = { 'b', 'i', 'r', 't', 'h', ' ', 'd', 'a', LineString 17 copies Linecharacter 18 Constructor copies array }; byte byteArray[] = { ( byte ) 'n', ( byte ) 'e', ( byte ) 'w', ( byte ) ' ', ( byte ) 'y', ( byte ) 'e', ( byte ) 'a', ( byte ) 'r' }; Line 19 Constructor copies character-array subset Line 20 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, ); s5 = new String( byteArray, 4, ); s6 = new String( byteArray ); Line Constructor copies byte21array Line 22 Constructor copies byte-array subset 2003 Prentice Hall, Inc All rights reserved 23 24 // append Strings to output 25 String output = "s1 = " + s1 + "\ns2 = " + s2 + "\ns3 = " + s3 + 26 "\ns4 = " + s4 + "\ns5 = " + s5 + "\ns6 = " + s6; 27 28 JOptionPane.showMessageDialog( null, output, 29 "String Class Constructors", JOptionPane.INFORMATION_MESSAGE ); 30 31 System.exit( ); 32 } 33 34 } // end class StringConstructors Outline StringConstruct ors.java 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 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 8 10 11 12 13 14 15 16 17 18 19 20 21 22 // Fig 11.2: StringMiscellaneous.java // This program demonstrates the length, charAt and getChars // methods of the String class import javax.swing.*; Outline StringMiscellan eous.java public class StringMiscellaneous { Line 16 public static void main( String args[] ) { String s1 = "hello there"; char charArray[] = new char[ ]; 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 s1’s 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 Outline // copy characters from string into charArray Copy (some of) s1’s s1.getChars( 0, 5, charArray, ); characters to charArray output += "\nThe character array is: "; StringMiscellan eous.java for ( int count = 0; count < charArray.length; count++ ) output += charArray[ count ]; Line 25 JOptionPane.showMessageDialog( null, output, "String class character manipulation methods", JOptionPane.INFORMATION_MESSAGE ); System.exit( ); } } // end class StringMiscellaneous 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 83 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 Elevator’s Door – i.e., Door is “notified” that Elevator has arrived • Action: Elevator’s 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 84 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.*; Represents an event in elevator simulation public class ElevatorSimulationEvent { Line Line 11 // Location that generated ElevatorSimulationEvent Location object reference represents location where even private Location location; was generated Line 14 // source of generated ElevatorSimulationEvent private Object source; Object object reference represents Location object that generated event // ElevatorSimulationEvent constructor sets public ElevatorSimulationEvent( Object source, Location location ) { setSource( source ); setLocation( location ); } 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 // set ElevatorSimulationEvent Location public void setLocation( Location eventLocation ) { location = eventLocation; } Outline 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 87 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 88 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 89 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 90 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 91 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 ) : elevatorArrived( ElevatorMoveEvent ) waitingPassenger : Person ridingPassenger : Person : Elevator e : or leva M to ov rA eE rr ve i ve nt d( ) El ev at 1.1: resetButton( ) 2003 Prentice Hall, Inc All rights reserved 3.3.1 : exitElevator( ) a ev El d( ve ) rri nt rA e to Ev : 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 ) 92 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 93 10 11 12 13 14 15 // ElevatorMoveEvent.java // Indicates on which Floor the Elevator arrived or departed package com.deitel.jhtp5.elevator.event; // Deitel package import com.deitel.jhtp5.elevator.model.*; Outline ElevatorMoveEve nt.java public class ElevatorMoveEvent extends ElevatorSimulationEvent { // ElevatorMoveEvent constructor public ElevatorMoveEvent( Object source, Location location ) { super( source, location ); } } 2003 Prentice Hall, Inc All rights reserved 10 11 12 // ElevatorMoveListener.java // Methods invoked when Elevator has either departed or arrived package com.deitel.jhtp5.elevator.event; public interface ElevatorMoveListener { Outline ElevatorMoveLis tener.java // 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 96 Fig 11.31 Class diagram of our simulator (including event handling) Door 1 Signalsar rival Turns on/off Light Resets Signals arrival 1 Opens / Closes Signals arrival ElevatorShaft 2 Button Presses 1 Informs of opening Person 1 Opens/Closes 1 Elevator ElevatorDoor Signals arrival Signals arrival Ring s 1 Signals to move Bell 2003 Prentice Hall, Inc All rights reserved 1 Occupies Signals arrival Location Floor 97 ... 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... StringIndexMethods .java // String searching methods indexOf and lastIndexOf import javax.swing.*; StringIndexMeth public class StringIndexMethods { ods .java public static void main( String args[] ) Lines 1 2-1 6... 11.2: StringMiscellaneous .java // This program demonstrates the length, charAt and getChars // methods of the String class import javax.swing.*; Outline StringMiscellan eous .java public class StringMiscellaneous