Scrigroup - Documente si articole

     

HomeDocumenteUploadResurseAlte limbi doc
AccessAdobe photoshopAlgoritmiAutocadBaze de dateCC sharp
CalculatoareCorel drawDot netExcelFox proFrontpageHardware
HtmlInternetJavaLinuxMatlabMs dosPascal
PhpPower pointRetele calculatoareSqlTutorialsWebdesignWindows
WordXml

AspAutocadCDot netExcelFox proHtmlJava
LinuxMathcadPhotoshopPhpSqlVisual studioWindowsXml

Using Strings to Communicate

java



+ Font mai mare | - Font mai mic



Using Strings to Communicate

In the film The Piano, Holly Hunter portrays Ada, a young Scottish woman who marries badly. A mute since the age of 6, Ada can only express herself fully by playing her prized possession, a piano. Like Ada, your computer programs are capable of quietly doing their work and never stopping for a chat--or piano recital--with humans. However, if The Piano teaches us anything, it is that communication ranks up there with food, water, and shelter as essential needs. (It also teaches us that Harvey Keitel has a lot of body confidence, but that's a matter for another book.)



Java programs don't have access to a piano. They use strings as the primary means to communicate with users. Strings are collections of text--letters, numbers, punctuation, and other characters. During this hour, you will learn all about working with strings in your Java programs. The following topics will be covered:

Using strings to store text

Displaying strings in a program

Including special characters in a string

Pasting two strings together

Including variables in a string

Some uses for strings

Comparing two strings

Determining the length of a string

Changing a string to uppercase or lowercase

Storing Text in Strings

Strings are a common feature in computer programming because they provide a way to store text and present it to users. The most basic element of a string is a character. A character is a single letter, number, punctuation mark, or other symbol.

In Java programs, a character is one of the types of information that can be stored in a variable. Character variables are created with the char type in a statement such as the following:

char keyPressed;

This statement creates a variable named keyPressed that can store a character. When you create character variables, you can set them up with an initial value, as in the following:

char quitKey = `@';

Note that the value of the character must be surrounded by single quotation marks. If it isn't, the javac compiler tool will respond with an error when the program is compiled.

A string is a collection of characters. You can set up a variable to hold a string value by using the String text and the name of the variable, as in the following statement:

String fullName = 'Ada McGrath Stewart';

This statement creates a String variable called fullName and stores the text Ada McGrath Stewart in it, which is the full name of Hunter's pianist. In a Java statement, a string is denoted with double quotation marks around the text. These quote marks will not be included in the string itself.

Unlike the other types of variables that you have used--int, float, char, boolean, and so on--the String type is capitalized. The reason for this is that strings are somewhat different than the other variable types in Java. Strings are a special resource called objects, and the types of all objects are capitalized. You'll be learning about objects during Hour 10, 'Creating Your First Object.' The important thing to note during this hour is that strings are different than the other variable types, and because of this difference, String is capitalized when strings are used in a statement.

Displaying Strings in Programs

The most basic way to display a string in a Java program is with the System.out.println() statement. This statement takes any strings and other variables inside the parentheses and displays them. The following statement displays a line of text to the system output device, which is the computer's monitor:

System.out.println('Silence affects everyone in the end.');

The preceding statement would cause the following text to be displayed:

Silence affects everyone in the end.

Displaying a line of text on the screen is often called printing, which is what println() stands for--'print this line.' You can use the System.out.println() statement to display text within double quotation marks and also to display variables, as you will see. Put all material that you want to be displayed within the parentheses.

Using Special Characters in Strings

When a string is being created or displayed, its text must be enclosed within double quotation marks to indicate the beginning and end of the string. These quote marks are not displayed, which brings up a good question: What if you want to display double quotation marks?

In order to display them, Java has created a special code that can be put into a string: . Whenever this code is encountered in a string, it is replaced with a double quotation mark. For example, examine the following:

System.out.println('Jane Campion directed 'The Piano' in 1993.');

This code is displayed as the following:

Jane Campion directed 'The Piano' in 1993.

You can insert several special characters into a string in this manner. The following list shows these special characters; note that each is preceded by a backslash ().

Special charactersDisplay Single quotation mark Double quotation mark BackslashtTabbBackspacerCarriage returnfFormfeednNewline
The newline character causes the text following the newline character to be displayed at the beginning of the next line. Look at this example:

System.out.println('Music bynMichael Nyman');

This statement would be displayed as the following:

Music by

Michael Nyman

Pasting Strings Together

When you use the System.out.println() statement and handle strings in other ways, you will sometimes want to paste two strings together. You do this by using the same operator that is used to add numbers: .

The operator has a different meaning in relation to strings. Instead of trying to do some math, it pastes two strings together. This action can cause strings to be displayed together, or it can make one big string out of two smaller ones. Concatenation is a word used to describe this action, because it means to link two things together. You'll probably see this term in other books as you build your programming skills, so it's worth knowing. However, pasting is the term used here to describe what happens when one string and another string decide to get together. Pasting sounds like fun. Concatenating sounds like something that should never be done in the presence of an open flame.

The following statement uses the operator to display a long string:

System.out.println('''The Piano' is as peculiar and haunting as any film ' +

'I've seen.'nt-- Roger Ebert, 'Chicago Sun-Times'');

Instead of putting this entire string on a single line, which would make it harder to understand when you look at the program later, the operator is used to break up the text over two lines of the program's Java text file. When this statement is displayed, it will appear as the following:

'`The Piano' is as peculiar and haunting as any film I've seen.'

-- Roger Ebert, `Chicago Sun-Times'

Several special characters are used in the string: , , n, and t. To better familiarize yourself with these characters, compare the output with the System.out.println() statement that produced it.

Using Other Variables with Strings

Although you can use the operator to paste two strings together, as demonstrated in the preceding section, you will use it more often to link strings and variables. Take a look at the following:

int length = 121;

char rating = `R';

System.out.println('Running time: ' + length + ' minutes');

System.out.println('Rated ' + rating);

This code will be displayed as the following:

Running time: 121 minutes

Rated R

This example displays a unique facet about how the operator works with strings. It can allow variables that are not strings to be treated just like strings when they are displayed. The variable length is an integer set to the value 121. It is displayed between the strings Running time: and minutes. The System.out.println() statement is being asked to display a string plus an integer plus another string. This statement works because at least one part of the group is a string. The Java language offers this functionality to make displaying information easier.

One thing that you might want to do with a string is paste something to it several times, as in the following example:

String searchKeywords = '';

searchKeywords = searchKeywords + 'drama ';

searchKeywords = searchKeywords + 'romance ';

searchKeywords = searchKeywords + 'New Zealand ';

This code would result in the searchKeywords variable being set to drama romance New Zealand. The first line creates the searchKeywords variable and sets it to be an empty string because there's nothing between the double quotation marks. The second line sets the searchKeywords variable equal to its current string plus the string drama added to the end. The next two lines add romance and New Zealand in the same way.

As you can see, when you are pasting more text at the end of a variable, the name of the variable has to be listed twice. Java offers a shortcut to simplify this process a bit: the operator. The operator combines the functions of the and operators. With strings, it is used to add something to the end of an existing string. The searchKeywords example can be shortened by using , as shown in the following code:

String searchKeywords = '';

searchKeywords += 'drama ';

searchKeywords += 'romance ';

searchKeywords += 'New Zealand ';

This code produces the same result: searchKeywords is set to drama romance New Zealand.

Advanced String Handling

In addition to creating strings, pasting them together, and using them with other types of variables, there are several different ways you can examine a string variable and change its value. These advanced features are possible because strings are objects in the Java language. Working with strings develops skills that you'll be using to work with other objects later.

Comparing Two Strings

One thing you will be testing often in your programs is whether one string is equal to another. You do this by using equals() in a statement with both of the strings, as in this example:

String favorite = 'piano';

String guess = 'ukelele';

System.out.println('Is Ada's favorite instrument a ' + guess + '?');

System.out.println('Answer: ' + favorite.equals(guess));

This example uses two different string variables. One, favorite, is used to store the name of Ada's favorite instrument: a piano. The other, guess, is used to store a guess as to what her favorite might be. The guess is that Ada prefers the ukelele.

The third line displays the text Is Ada's favorite instrument a followed by the value of the guess variable and then a question mark. The fourth line displays the text Answer: and then contains something new:

favorite.equals(guess)

This part of the statement is known as a method. A method is a way to accomplish a task in a Java program. This method's task is to determine if one string, favorite, has the same value as another string, guess. If the two string variables have the same value, the text true will be displayed. If not, the text false will be displayed. The following is the output of this example:

Is Ada's favorite instrument a ukelele?

Answer: false

Determining the Length of a String

It can be useful at times to determine the length of a string in characters. You do this by using the length() method. This method works in the same fashion as the equals() method, except that only one string variable is involved. Look at the following example:

String cinematographer = 'Stuart Dryburgh';

int nameLength = cinematographer.length();

This example sets nameLength, an integer variable, equal to 15. The cinematographer.length() method counts the number of characters in the string variable called cinematographer, and this count is assigned to the nameLength integer variable.

Changing a Strings Case

Because computers take everything literally, it's easy to confuse them. Although a human would recognize that the text Harvey Keitel and the text HARVEY KEITEL are referring to the same thing, most computers would disagree. For instance, the equals() method discussed previously in this hour would state authoritatively that Harvey Keitel is not equal to HARVEY KEITEL.

To get around some of these obstacles, Java has methods that display a string variable as all uppercase letters (toUpperCase()) or all lowercase letters (toLowerCase()). The following example shows the toUpperCase() method in action:

String baines = 'Harvey Keitel';

String change = baines.toUpperCase();

This code sets the string variable change equal to the baines string variable converted to all uppercase letters--HARVEY KEITEL, in other words. The toLowerCase() method works in the same fashion but returns an all-lowercase string value.

Workshop: Presenting Credits

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 ivory tickling. You might have felt similarly lost with some of the topics introduced during this hour.

As a workshop to reinforce the string handling features that have been covered, you will write a Java program to display credits for a feature film. You have three guesses as to the movie chosen, and if you need a hint, it starts with a The and ends with a musical instrument that can be used to express the repressed passion of attractive mutes.

Load the word processor you're using to write Java programs and create a new file called Credits.java. Enter the text of Listing 6.1 into the word processor and save the file when you're done.

Listing 6.1. The Credits program.

1: class Credits


Before you attempt to compile the program with the javac tool, look over the program and see whether you can figure out what it's doing at each stage. Here's a breakdown of what's taking place:

Line 1 gives the Java program the name Credits.

Line 2 begins the main() block statement in which all of the program's work gets done.

Line 3 is a comment statement explaining that you're going to set up the film's information in subsequent lines.

Lines 4-14 set up variables to hold information about the film, its director, and its stars. One of the variables, year, is an integer. The rest are string variables.

Line 15 is another comment line for the benefit of humans like us examining the program.

Lines 16-21 are one long System.out.println() statement. Everything between the first parenthesis on Line 16 and the last parenthesis on Line 21 is displayed on-screen. The newline text (n) causes the text after it to be displayed at the beginning of a new line. The Tab text (t) inserts Tab spacing in the output. The rest is either text or string variables that should be shown.

Line 22 ends the main() block statement.

Line 23 ends the program.

Attempt to compile the program by going to the directory that contains Credits.java and typing this command:

javac Credits.java

If you do not see any error messages, the program has compiled successfully, and you can run it with the following command:

java Credits

If you do encounter error messages, correct any typos that you find in your version of the Credits program and try again to compile it.

Listing 6.2 shows the output of the Credits program: a rundown of the film, year of release, director, and the four lead performers from The Piano. Be glad that you didn't have to present the credits for an ensemble film. A program detailing Robert Altman's Short Cuts, the 1993 film with more than 25 lead characters, could hog an hour on typing alone.

Listing 6.2. The output of the Credits program.

The Piano 1993

A Jane Campion film.

Ada Holly Hunter

Baines Harvey Keitel

Stewart Sam Neill

Flora Anna Paquin

If this hour's trivia related to The Piano and the films of director Jane Campion has sparked your curiosity, or if you just dig quiet women in braids, visit the following World Wide Web sites: n Magnus Hjelstuen's unofficial The Piano Web site, with cast descriptions, storyline discussion, and comprehensive details about his favorite movie:

<https://www.ifi.uio.no/~magnush/Piano/>

n The Internet Movie Database, a voluminous yet searchable database of movies, TV shows, actors, directors, yet other related topics:

<https://www.imdb.com>

Summary

Once your version of Credits works like the one shown in Listing 6.2, give yourself some credits, too. You're writing longer Java programs and dealing with more sophisticated issues each hour. Like variables, strings are something you'll use every time you sit down to write a program.

At the beginning of The Piano, Holly Hunter's Ada lost her piano when her new husband refused to make his Maori laborers carry it home. Luckily for you, the ability to use strings in your Java programs cannot be taken away by an insensitive newlywed or anyone else. You'll be using strings in many ways to communicate with users.

Q&A

Q In addition to System.out.println(), what are some other ways to display strings in Java programs?

A
Strings can be displayed using different means in Java programs that run on World Wide Web pages and in programs that have a graphical user interface. Web page Java programs, which are called applets, rely on a method called drawString() to display text. Hour 13, 'Learning How Applets Work,' covers several programming features that are specific to applet programming. Programs that have a graphical user interface display strings by putting them into a text-entry field or displaying them as a label next to some other part of the program's window.

Q How can I set the value of a string variable to be blank?

A
A pair of double quotation marks without any text between them is considered to be an empty string. You can set a string variable equal to this upon its creation or in other parts of your programs. The following code creates a new string variable called
adaSays and sets it to nothing:

String adaSays = '';

Q Is there a way to make the text in one println() statement start right at the end of the text in the preceding println() statement? I don't want the second println() statement to start at the beginning of a new line, but it always does.

A
Java automatically starts each System.out.println() statement on its own new line, so the only way to prevent this is to use a statement that includes all of the text you want to display. The Credits program from the workshop has an example of a println() statement that includes several different lines of output. Take a look at it and see whether it fits what you want to do.

Q If the + operator is used with strings to link up two different strings, can you add the numeric value of one string to the value of another?

A
You can use the value of a
String variable as an integer only by using a method that
converts the string's value into a numeric form. This procedure is called casting because it recasts existing information, in this case a string, as a different type of information.

Q Is it necessary to use += instead of + when adding some text to a string variable?

A
Not at all. The
operator is strictly for the benefit of programmers who want to use it as a shortcut. If you're more comfortable using the operator when pasting some added text to a string variable, you ought to stick with it. The time and convenience you can gain by using will be lost pretty quickly if it causes you to make errors in your program.

Q Isn't there some kind of == operator that can be used to determine whether two strings have the same value, as in daughter == 'Flora'?

A
As you will discover during the next hour, 'Using Conditional Tests to Make Decisions,' the
operator can be used with all of the variable types except for strings. The reason for the difference is that strings are objects. Java treats objects differently than other types of information, so special methods are necessary to determine whether one string is equal to another.

Q Do all methods in Java display true or false in the same way that the equals() method does in relation to strings?

A
Methods have different ways of making a response after they are used. When a method sends back a value, as the
equals() method does, this is called returning a value. The equals() method is set to return a Boolean value. Other methods might return a string, an integer, another type of variable, or nothing at all.

Quiz

The following questions will test your knowledge of the care and feeding of a string.

Questions

My friend concatenates. Should I report him to the authorities?

(a)
No. It's illegal only during the winter months.
(b) Yes, but not until I sell my story to Hard Copy first.
(c) No. All he's doing is pasting two strings together in a program.

2.
Why is the word
String capitalized while int and others are not?

(a)
String is a full word, but int ain't.
(b) Like all objects in Java,
String has a capitalized name.
(c) Poor quality control at JavaSoft.

3.
Which of the following characters will put a single quote in a string?

(a)
<QUOTE>
(b)
(c)

Answers

c. Concatenation is just another word for pasting, joining, melding, or otherwise connecting two strings together. It uses the and operators.

2.
b. The types of objects available in Java are all capitalized, which is the main reason variable names have a lowercase first letter. It makes it harder to mistake them for objects.

3.
b. The single backslash is what begins one of the special characters that can be inserted into strings.

Activities

You can review the topics of this hour more fully with the following activities:

Write a short Java program called Favorite that puts the code from this hour's 'Comparing Two Strings' section into the main() block statement. Test it out to make sure it works as described and says that Ada's favorite instrument is not the ukelele. Then, change the initial value of the guess variable from ukelele to piano. See what happens.

Modify the Credits program so that the names of the director and all performers are displayed entirely in uppercase letters.



Politica de confidentialitate | Termeni si conditii de utilizare



DISTRIBUIE DOCUMENTUL

Comentarii


Vizualizari: 1454
Importanta: rank

Comenteaza documentul:

Te rugam sa te autentifici sau sa iti faci cont pentru a putea comenta

Creaza cont nou

Termeni si conditii de utilizare | Contact
© SCRIGROUP 2024 . All rights reserved