Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

72 HOUR 6:Using Strings to Communicate


One possible use of the indexOf()method would be to search the entire
script of The Pianofor the place where Ada’s domineering husband tells
her daughter Flora, “You are greatly shamed and you have shamed those
trunks.”
If the entire script of The Pianowas stored in a string called script, you
could search it for part of that quote with the following statement.
int position = script.indexOf(“you have shamed those trunks”);

If that text can be found in the scriptstring, positionequals the position
at which the text “you have shamed those trunks” begins. Otherwise, it
will equal -1.

Presenting Credits
In The Piano, Ada McGrath Stewart was thrown into unfamiliar territory
when she moved from Scotland to New Zealand to marry a stranger who
didn’t appreciate her music. You might have felt lost yourself with some of
the topics introduced during this hour.
Next, to reinforce the string-handling features that have been covered, you
write a Java program to display credits for a feature film. You can probably
guess the movie.
Return to the Java24project in NetBeans and create a new Java class called
Credits. Enter the text of Listing 6.1 into the source editor and save the file
when you’re done.

LISTING 6.1 TheCreditsProgram
1: classCredits {
2: public static voidmain(String[] args) {
3: // set up film information
4: String title = “The Piano”;
5: int year = 1993;
6: String director = “Jane Campion”;
7: String role1 = “Ada”;
8: String actor1 = “Holly Hunter”;
9: String role2 = “Baines”;
10: String actor2 = “Harvey Keitel”;
11: String role3 = “Stewart”;
12: String actor3 = “Sam Neill”;
13: String role4 = “Flora”;
14: String actor4 = “Anna Paquin”;
15: // display information
16: System.out.println(title + “ (“+ year + “)\n” +
17: “A “+ director + “ film.\n\n” +

CAUTION
TheindexOf()method is case-
sensitive, which means that it
only looks for text capitalized
exactly like the search string. If
the string contains the same text
capitalized differently,indexOf()
produces the value -1.

Free download pdf