Archive for December, 2007

Affordable web hosting - 594 Strings and Characters Chapter 10 SELF-REVIEW EXERCISES

Sunday, December 9th, 2007

594 Strings and Characters Chapter 10 SELF-REVIEW EXERCISES 10.1 State whether each of the following is true or false. If false, explain why. a) When String objects are compared with ==, the result is true if the Strings contain the same values. b) A String can be modified after it is created. 10.2 For each of the following, write a single statement that performs the indicated task. a) Compare the string in s1 to the string in s2 for equality of contents. b) Append the string s2 to the string s1, using +=. c) Determine the length of the string in s1. ANSWERS TO SELF-REVIEW EXERCISES 10.1 a) False. String objects that are compared with operator == are actually compared to determine if they are the same object in memory. b) False. String objects are constant and cannot be modified after they are created. StringBufferobjects can be modified after they are created. 10.2 a) s1.equals( s2 ) b) s1 += s2; c) s1.length() EXERCISES Exercises 10.3 through 10.6 are reasonably challenging. Once you have done these problems, you ought to be able to implement most popular card games easily. 10.3 Modify the program in Fig. 10.21 so that the card-dealing method deals a five-card poker hand. Then write the following additional methods: a) Determine if the hand contains a pair. b) Determine if the hand contains two pairs. c) Determine if the hand contains three of a kind (e.g., three jacks). d) Determine if the hand contains four of a kind (e.g., four aces). e) Determine if the hand contains a flush (i.e., all five cards of the same suit). f) Determine if the hand contains a straight (i.e., five cards of consecutive face values). g) Determine if the hand contains a full house (i.e., two cards of one face value and three cards of another face value). 10.4 Use the methods developed in Exercise 10.3 to write a program that deals two five-card poker hands, evaluates each hand and determines which is the better hand. 10.5 Modify the program developed in Exercise 10.4 so that it can simulate the dealer. The dealer s five-card hand is dealt face down so the player cannot see it. The program should then evaluate the dealer s hand and, based on the quality of the hand, the dealer should draw one, two or three more cards to replace the corresponding number of unneeded cards in the original hand. The program should then reevaluate the dealer s hand. (Caution: This is a difficult problem!) 10.6 Modify the program developed in Exercise 10.5 so that it can handle the dealer s hand automatically, but the player is allowed to decide which cards of the player s hand to replace. The program should then evaluate both hands and determine who wins. Now, use this new program to play 20 games against the computer. Who wins more games, you or the computer? Have one of your friends play 20 games against the computer. Who wins more games? Based on the results of these games, make appropriate modifications to refine your poker-playing program. (This, too, is a difficult problem.) Play 20 more games. Does your modified program play a better game? Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Chapter 10 Strings and Characters (Cheapest web hosting) 593 StringTokenizermethod

Saturday, December 8th, 2007

Chapter 10 Strings and Characters 593 StringTokenizermethod countTokens returns the number of tokens in a String to be tokenized. StringTokenizer method hasMoreTokens determines if there are more tokens in the String being tokenized. StringTokenizermethod nextToken returns a String with the next token. TERMINOLOGY append method of class StringBuffer isUpperCase method of class Character appending strings to other strings lastIndexOf method of class String array of strings length method of class String capacity method of class StringBuffer length method of class StringBuffer Character class length of a string character code literal character constant nextTokenmethod of StringTokenizer character set numeric code representation of a character charAt method of class String printing character charAt method of class StringBuffer regionMatches method of class String charValue method of class Character replace method of class String compareTo method of class String search string comparing strings setCharAt method of class StringBuffer concat method of class String startsWith method of class String concatenation string copying strings String class countTokens method (StringTokenizer) string concatenation delimiter string constant digit method of class Character string literal endsWith method of class String string processing equals method of class String StringBuffer class equalsIgnoreCase method of String StringIndexOutOfBoundsException forDigit method of class Character StringTokenizer class getChars method of class String substringmethod of String class getChars method of class StringBuffer toCharArray method of class String hash table token hashCode method of class Character tokenizing strings hashCode method of class String toLowerCase method of class Character hasMoreTokensmethod toLowerCase method of class String hexadecimal digits toString method of class Character indexOf method of class String toString method of class String insert method of class StringBuffer toString method of class StringBuffer intern method of class String toUpperCase method of class Character isDefined method of class Character toUpperCase method of class String isDigit method of class Character trim method of class String isJavaIdentifierPartmethod Unicode isJavaIdentifierStartmethod valueOf method of class String isLetter method of class Character white-space characters isLetterOrDigit method of Character word processing isLowerCase method of class Character Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

592 Strings and Characters Chapter 10 Class StringBuffer (Web hosting uk)

Friday, December 7th, 2007

592 Strings and Characters Chapter 10 Class StringBuffer provides three constructors that enable StringBuffers to be initialized with no characters and an initial capacity of 16 characters; with no characters and an initial capacity specified in the integer argument or with a copy of the characters of the String argument and an initial capacity that is the number of characters in the Stringargument plus 16. StringBuffer method length returns the number of characters currently stored in a StringBuffer. Method capacity returns the number of characters that can be stored in a StringBufferwithout allocating more memory. Method ensureCapacity ensures that a StringBuffer has a minimum capacity. Method setLengthincreases or decreases the length of a StringBuffer. StringBuffer method charAt returns the character at the specified index. Method set- CharAt sets the character at the specified position. Method getChars returns a character array containing a copy of the characters in the StringBuffer. Class StringBuffer provides overloaded append methods to add primitive data-type, character array, String and Objectvalues to the end of a StringBuffer. StringBuffers and the append methods are used by the Java compiler to implement the + and += operators for concatenating Strings. Class StringBuffer provides overloaded insert methods to insert primitive data-type, character array, String and Object values at any position in a StringBuffer. Class Characterprovides a constructor that takes a character argument. Character method isDefined determines whether a character is defined in the Unicode character set. If so, the method returns true; otherwise, it returns false. Charactermethod isDigit determines whether a character is a defined Unicode digit. If so, the method returns true; otherwise, it returns false. Character method isJavaIdentifierStart determines whether a character is a character that can be used as the first character of an identifier in Java [i.e., a letter, an underscore (_) or a dollar sign ($)]. If so, the method returns true; otherwise, it returns false. Charactermethod isJavaIdentifierPartdetermines whether a character is a character that can be used in an identifier in Java [i.e., a digit, a letter, an underscore (_) or a dollar sign ($)]. If so, the method returns true; otherwise, it returns false. Method isLetter determines whether a character is a letter. If so, the method returns true; otherwise, it returns false. Method isLetterOrDigit determines whether a character is a letter or a digit. If so, the method returns true; otherwise, it returns false. Charactermethod isLowerCase determines whether a character is a lowercase letter. If so, the method returns true; otherwise, false. Charactermethod isUpperCase determines if a character is an uppercase letter. If so, the method returns true; otherwise, false. Character method toUpperCase converts a character to its uppercase equivalent. Method toLowerCase converts a character to its lowercase equivalent. Charactermethod digit converts its character argument into an integer in the number system specified by its integer argument radix. Method forDigit converts its integer argument digitinto a character in the number system specified by its integer argument radix. Character method charValue returns the char stored in a Character object. Method toString returns a Stringrepresentation of a Character. Charactermethod hashCode performs a hash code calculation on a Character. StringTokenizer s default constructor creates a StringTokenizer for its String argument that will use the default delimiter string “ntr”, consisting of a space, a newline, a tab and a carriage return for tokenization. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Chapter 10 Strings and Characters 591 SUMMARY (Web page design)

Friday, December 7th, 2007

Chapter 10 Strings and Characters 591 SUMMARY A character constant s value is its integer value in the Unicode character set. Strings can include letters, digits and special characters such as +, -, *, / and $. A string in Java is an object of class String. String literals or string constants are often referred to as anonymous String objects and are written in double quotes in a program. Class String provides nine constructors. String method length returns the number of characters in a String. String method charAtreturns the character at a specific position. Method equalsis used to test any two objects for equality (i.e., the contents of the two objects are identical). The method returns true if the objects are equal, false otherwise. Method equals uses a lexicographical comparison for Strings. When primitive-data type values are compared with ==, the result is true if both values are identical. When references are compared with ==, the result is true if both references refer to the same object in memory. Java treats all anonymous Strings with the same contents as one anonymous String object. String method equalsIgnoreCase performs a case-insensitive String comparison. String method compareTo returns 0 if the Strings it is comparing are equal, a negative number if the String that invokes compareTo is less than the String that is passed as an argument and a positive number if the String that invokes compareTo is greater than the String that is passed as an argument. Method compareTo uses a lexicographical comparison. String method regionMatchescompares portions of two Strings for equality. Stringmethod startsWith determines whether a String starts with the characters specified as an argument. String method endsWith determines whether a String ends with the characters specified as an argument. Method hashCode performs a hash code calculation that enables a String object to be stored in a hash table. This method is inherited from Objectand overridden by String. Stringmethod indexOf locates the first occurrence of a character or a substring in a String. Method lastIndexOf locates the last occurrence of a character or a substring in a String. String method substringcopies and returns part of an existing Stringobject. String method concat concatenates two String objects and returns a new Stringobject containing the characters from both original Strings. String method replace returns a new String object that replaces every occurrence in a Stringof its first character argument with its second character argument. Stringmethod toUpperCase returns a new String with uppercase letters in the positions where the original String had lowercase letters. Method toLowerCase returns a new String with lowercase letters in the positions where the original String had uppercase letters. String method trim returns a new String object in which all white-space characters (such as spaces, newlines and tabs) have been removed from the beginning or end of a String. Stringmethod toCharArray returns a new character array containing a copy of the characters in a String. String class method valueOfreturns its argument converted to a string. The first time String method intern is invoked on a String it returns a reference to that String object. Subsequent invocations of intern on different String objects that have the same contents as the original String result in multiple references to the original String object. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Hosting web - 590 Strings and Characters Chapter 10 Class Diagram

Thursday, December 6th, 2007

590 Strings and Characters Chapter 10 Class Diagram Revisited Figure 10.29 modifies the associations in the class diagram of Fig. 9.19 to include event handling. Note that like the collaboration diagram of Fig. 10.26, Fig. 10.29 indicates that an object informs, or signals, another object that some event has occurred. If an object receiving the event invokes a private method, the class diagram represents this method invocation as a self association that is, the class contains an association with itself. The Button, Door, Lightand Bellclasses contain self associations; note that the association does not include an arrowhead indicating the direction of the association, because the class s association is with itself. Lastly, the diagram includes an association between class Door and class Person (the Door informs a Person that the Door has opened), because we established the relationship between all Doorobjects and a Personobject. Creates Light ElevatorModel Floor ElevatorShaft Bell Person Elevator Presses 2 2 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0..* 1 1 1 1 2 Signals to move ResetsOpens / Closes Occupies Signals arrival Turns on/off Rings Door Button LocationSignals arrival Signals arrival Signals arrival Signals arrival Signals arrival Informs of opening 1 1 1 1 1 1 1 1 1 1 Fig. 10.29Class diagram of our simulator (including event handling). 10.29 Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Chapter 10 Strings and (Adelphia web hosting) Characters 589 1 //

Wednesday, December 5th, 2007

Chapter 10 Strings and Characters 589 1 // ElevatorMoveEvent.java 2 // Indicates on which Floor the Elevator arrived or departed 3 package com.deitel.jhtp4.elevator.event; 4 5 // Deitel package 6 import com.deitel.jhtp4.elevator.model.*; 7 8 public class ElevatorMoveEvent extends ElevatorModelEvent { 9 10 // ElevatorMoveEvent constructor 11 public ElevatorMoveEvent( Object source, Location location ) 12 { 13 super( source, location ); 14 } 15 } Fig. 10.27 Class ElevatorMoveEvent, a subclass of ElevatorModelEvent, is sent when the Elevatorhas arrived at or departed from, a Floor. The elevatorDoormust implement an interface that listens for an Elevator- MoveEvent this makes the elevatorDooran event listener. Interface Elevator- MoveListener (Fig. 10.28) provides methods elevatorDeparted (line 8) and elevatorArrived (line 11) that enable the Elevator to notify the Elevator- MoveListenerwhen the Elevatorhas arrived or departed. An interface that provides the methods for an event listener, such as ElevatorMoveListener, is called an event listener interface. Methods elevatorArrived and elevatorDeparted each receive an ElevatorMoveEvent(Fig. 10.27) object as an argument. Therefore, when the Elevator sends an elevatorArrivedevent to another object, the Elevatorpasses an ElevatorMoveEventobject as an argument to the receiving object s elevatorArrived method. We implement class Door the class of which the elevatorDoor is an instance in Appendix H, after we continue refining our design and learning more Java capabilities. 1 // ElevatorMoveListener.java 2 // Methods invoked when Elevator has either departed or arrived 3 package com.deitel.jhtp4.elevator.event; 4 5 public interface ElevatorMoveListener { 6 7 // invoked when Elevator has departed 8 public void elevatorDeparted( ElevatorMoveEvent moveEvent ); 9 10 // invoked when Elevator has arrived 11 public void elevatorArrived( ElevatorMoveEvent moveEvent ); 12 } Fig. 10.28 Interface ElevatorMoveListenerprovides the methods required to listen for Elevatordeparture and arrival events. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Web design - 588 Strings and Characters Chapter 10 ically, the

Wednesday, December 5th, 2007

588 Strings and Characters Chapter 10 ically, the Elevator object sends an ElevatorMoveEvent using the receiving object s elevatorArrived method. Figure 10.26 begins with the Elevator sending an elevatorArrived event to the elevatorButton. The elevatorButton then resets itself (message 1.1). The Elevator then sends an elevatorArrived event to the Bell (message 2), and the Bell invokes its ringBell method, accordingly (i.e., the Bell object sends itself a ringBell message in message 2.1). The Elevator sends an elevatorArrived message to the elevatorDoor (message 3). The elevatorDoor then opens itself by invoking its openDoor method (message 3.1). At this point, the elevatorDoor is open but has not informed the ridingPassenger of opening. Before informing the ridingPassenger, the elevatorDoor opens the firstFloorDoor by sending an openDoor message to the firstFloorDoor (message 3.2) this guarantees that the ridingPassenger will not exit before the firstFloorDoor opens. The firstFloorDoor then informs the waitingPassenger that the firstFloorDoor has opened (message 3.2.1), and the waitingPassenger enters the Elevator (message 3.2.1.1). All messages nested in 3.2 have been passed, so the elevatorDoor may inform the ridingPassenger that elevatorDoor has opened by invoking method doorOpened of the ridingPassenger (message 3.3). The ridingPassengerresponds by exiting the Elevator (message 3.3.1).2 Lastly, the Elevator informs the ElevatorShaft of the arrival (message 4). The ElevatorShaft then informs the firstFloorButton of the arrival (message 4.1), and the firstFloorButton resets itself (message 4.1.1). The Elevator- Shaft then informs the firstFloorLight of the arrival (message 4.2), and the firstFloorLightilluminates itself (message 4.2.1). Event Listeners We demonstrated event handling between the Elevator and object elevatorDoorusing the modified collaboration diagram of Fig. 10.26 the Elevator sends an elevatorArrived event to the elevatorDoor (message 3). We first must determine the event object that the Elevator will pass to the elevatorDoor. According to the note in the lower left-hand corner of Fig. 10.26, the Elevator passes an Elevator- MoveEvent(Fig. 10.27) object when the Elevator invokes an elevatorArrived method. The generalization diagram of Fig. 10.24 indicates that ElevatorMoveEvent is a subclass of ElevatorModelEvent, so ElevatorMoveEvent inherits the Object and Location references from ElevatorModelEvent.3 2. The problem of the waitingPassenger entering the Elevator (message 3.2.1.1) before the ridingPassenger has exited (message 3.3.1) remains in our collaboration diagram. We show in Thinking About Objects Section 15.12 how to solve this problem by using multithreading, synchronization and active classes. 3. In our simulation, all event classes have this structure that is, the structure of class Elevator- MoveEvent is identical to the structure of class DoorEvent, ButtonEvent, etc. When you have finished reading the material in this section, we recommend that you view the implementation of the events in Appendix G to attain a better comprehension of the structure of our system events Fig. G.1 G.7 present the code for the events, and Fig. G.8 G.14 present the code for the event listeners. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Chapter 10 Strings and Characters 587 (DoorEvent) 3.2.1 (Web site directory)

Tuesday, December 4th, 2007

Chapter 10 Strings and Characters 587 <
> (DoorEvent) 3.2.1 doorOpened( ) 3.2 : openDoor( ) firstFloorLight: Light elevatorDoor: Door : ElevatorShaft : Elevator : Bell firstFloorButton : Button elevatorButton: Button waitingPassenger : Person firstFloorDoor : Door ridingPassenger : Person 4.2.1 : turnOnLight( )4.1.1 : resetButton( ) 3.3.1 : exitElevator( )3.2.1.1 : enterElevator( ) 4 : elevatorArrived( ) 3 : elevator Arrived( ) 3.3 : doorOpened( ) 3.1: openDoor( ) 1 : elevatorArrived( ) 1.1: resetButton( ) 2 : elevator Arrived( ) 4.1 : elevatorArrived( ) 4.2 : elevatorArrived( ) 2.1: ringBell( ) <
> (ElevatorMoveEvent) <
> (Location) Fig. 10.26Modified collaboration diagram for passengers entering and exiting the 10.26 Elevatoron the first Floor. The second difference between the diagrams is that the interactions of Fig. 10.26 occur on the first Floor. This allows us to name all Button and Door objects (first- FloorDoor and firstFloorButton) to eliminate ambiguity, because the Button and Doorclasses each have three objects in our simulation. The interactions that occur on the second Floorare identical to the ones that occur on the first Floor. The most substantial difference between Fig. 10.26 and Fig. 7.25 is that the Elevatorinforms objects (via an event) of an action that has already happened the Elevator has arrived. The objects that receive the event then perform some action in response to the type of message they receive. According to messages 1, 2, 3 and 4, the Elevator performs only one action it sends elevatorArrivedevents to objects interested in receiving those events. Specif Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

586 Strings and Characters Chapter 10 Event Sent (Web hosting packages)

Monday, December 3rd, 2007

586 Strings and Characters Chapter 10 Event Sent when (triggering action) Sent by object of class BellEvent the Bellhas rung Bell ButtonEvent a Buttonhas been pressed Button a Buttonhas been reset Button DoorEvent a Doorhas opened Door a Doorhas closed Door LightEvent a Lighthas turned on Light a Lighthas turned off PersonMoveEvent a Personhas been created Person a Personhas arrived at the Elevator a Personhas entered the Elevator a Personhas exited the Elevator a Personhas pressed a Button a Personhas exited the simulation ElevatorMoveEvent the Elevatorhas arrived at a Floor Elevator the Elevatorhas departed from a Floor Fig. 10.25 Triggering actions of the ElevatorModelEventsubclass events. Event Handling The concept of event handling in Java is similar to the concept of a collaboration described in Section 7.10. Event handling consists of an object of one class sending a particular message (which Java calls an event) to objects of other classes listening for that type of message.1 The difference is that the objects receiving the message must register to receive the message; therefore, event handling describes how an object sends an event to other objects listening for that type of event these objects are called event listeners. To send an event, the sending object invokes a particular method of the receiving object while passing the desired event object as a parameter. In our simulation, this event object belongs to a class that extends ElevatorModelEvent. We presented a collaboration diagram in Fig. 7.25 showing interactions of two Personobjects waitingPassenger and ridingPassenger as they enter and exit the Elevator. Figure 10.26 shows a modified diagram that incorporates event handling. There are three differences between the diagrams. First, we provide notes explanatory remarks about some of the graphics in the diagram. The UML represents notes as rectangles with the upper right corners folded over. Notes in the UML are similar to comments in Java. A dotted line associates a note with any component of the UML (object, class, arrow, etc.). In this diagram, the <
>notation specifies that the note contains the parameters of a given message: all doorOpenedevents pass a DoorEvent object as a parameter; all elevatorArrived events pass an ElevatorMoveEvent object; all openDoormessages pass a Locationobject. 1. Technically, one object sends a notification of an event or some triggering action to another object. However, Java parlance refers to sending this notification as sending an event. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

1 on 1 web hosting - Chapter 10 Strings and Characters 585 35 36

Sunday, December 2nd, 2007

Chapter 10 Strings and Characters 585 35 36 // set ElevatorModelEvent source 37 private void setSource( Object eventSource ) 38 { 39 source = eventSource; 40 } 41 42 // get ElevatorModelEvent source 43 public Object getSource() 44 { 45 return source; 46 } 47 } Fig. 10.23 Class ElevatorModelEventis the superclass for all other event classes in our model (part 2 of 2). For example, a Door may send an ElevatorModelEvent to a Person when opening or closing, and the Elevatormay send an ElevatorModelEventinforming a person of a departure or arrival. Having different objects send the same event type to describe different actions could be confusing. To eliminate ambiguity as we discuss what events are sent by objects, we create several ElevatorModelEvent subclasses in Fig. 10.24, so we will have an easier time associating each event with its sender. According to Fig. 10.24, classes BellEvent, PersonMoveEvent, LightEvent, Button- Event, ElevatorMoveEvent and DoorEventare subclasses of class Elevator- ModelEvent. Using these event subclasses, a Door sends a different event (a DoorEvent) than does a Button (which sends a ButtonEvent). Figure 10.25 displays the triggering actions of the subclass events. Note that all actions in Fig. 10.25 appear in the form noun + verb . ElevatorModelEvent BellEvent DoorEvent PersonMoveEvent ButtonEvent ElevatorMoveEvent LightEvent Fig. 10.24Class diagram that models the generalization between 10.24 ElevatorModelEventand its subclasses. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01