AhmadLang / Java, How To Program, 2004
.pdf
startsWith method of class String
string literal
StringIndexOutOfBoundsException class
token of a String
toLowerCase method of class Character
toUpperCase method of class Character
trim method of class StringBuffer
Unicode character set
valueOf method of class String
word character
[Page 1391 (continued)]
Self-Review Exercises
29.1 State whether each of the following is true or false. If false, explain why.
a.When String objects are compared using ==, the result is true if the Strings contain the same values.
b.A String can be modified after it is created.
29.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.
[Page 1392]
Answers to Self-Review Exercises
29.1 a. False. String objects that are compared using operator == are compared to determine whether they are the same object in memory.
b.False. String objects are immutable and cannot be modified after they are created. StringBuffer objects can be modified after they are created.
29.2 a. s1.equals( s2 )
b.s1 += s2;
c.s1.length()
[Page 1392 (continued)]
Exercises
29.3Write an application that uses String method compareTo to compare two strings input by the user. Output whether the first string is less than, equal to or greater than the second.
29.4Write an application that uses String method regionMatches to compare two strings input by the user. The application should input the number of characters to be compared and the starting index of the comparison. The application should state whether the strings are equal. Ignore the case of the characters when performing the comparison.
29.5Write an application that uses random-number generation to create sentences. Use four arrays of strings called article, noun, verb and preposition. Create a sentence by selecting a word at random from each array in the following order: article, noun, verb, preposition, article and noun. As each word is picked, concatenate it to the previous words in the sentence. The words should be separated by spaces. When the final sentence is output, it should start with a capital letter and end with a period. The application should generate 20 sentences and output them to a text area.
The article array should contain the articles "the", "a", "one", "some" and "any"; the noun array should contain the nouns "boy", "girl", "dog", "town" and "car"; the verb array should contain the verbs "drove", "jumped", "ran", "walked" and "skipped"; the preposition array should contain the prepositions "to", "from",
"over", "under" and "on".
After the preceding application is written, modify it to produce a short story consisting of several of these sentences. (How about the possibility of a random term-paper writer?)
29.6(Limericks) A limerick is a humorous five-line verse in which the first and second lines rhyme with the fifth, and the third line rhymes with the fourth. Using techniques similar to those developed in Exercise 29.5, write a Java application that produces random limericks. Polishing this application to produce good limericks is a challenging problem, but the result will be worth the effort!
29.7(Pig Latin) Write an application that encodes English-language phrases into pig Latin. Pig Latin is a form of coded language. There are many different ways to form pig Latin phrases. For simplicity, use the following algorithm:
To form a pig Latin phrase from an English-language phrase, tokenize the phrase into words with an object of class StringTokenizer. To translate each English word into a pig Latin word, place the first letter of the English word at the end of the word and add the letters "ay." Thus, the word "jump" becomes "umpjay," the word "the" becomes "hetay," and the word "computer" becomes "omputercay." Blanks between words remain as blanks. Assume the following: The English phrase consists of words separated by blanks, there are no punctuation marks and all words have two or more letters. Method printLatinWord should display each word. Each token returned from nextToken is passed to method printLatinWord to print the pig Latin word. Enable the user to input the sentence. Keep a running display of all the converted sentences in a text area.
29.8Write an application that inputs a telephone number as a string in the form (555) 555-5555. The application should use an object of class StringTokenizer to extract the area code as a token, the first three digits of the phone number as a token and the last four digits of the phone number as a token. The seven digits of the phone number should be concatenated into one string. Both the area code and the phone number should be printed. Remember that you will have to change delimiter characters during the tokenization process.
[Page 1393]
29.9Write an application that inputs a line of text, tokenizes the line with an object of class StringTokenizer and outputs the tokens in reverse order. Use space characters as delimiters.
29.10Use the string-comparison methods discussed in this chapter and the techniques for sorting arrays developed in Chapter 16 to write an application that alphabetizes a list of strings. Allow the user to enter the strings in a text field. Display the results in a text area.
29.11Write an application that inputs a line of text and outputs the text twiceonce in all uppercase letters and once in all lowercase letters.
29.12Write an application that inputs a line of text and a search character and uses String method indexOf to determine the number of occurrences of the character in the text.
29.13Write an application based on the application in Exercise 29.12 that inputs a line of text and uses String method indexOf to determine the total number of occurrences of each letter of the alphabet in the text. Uppercase and lowercase letters should be counted together. Store the totals for each letter in an array, and print the values in tabular format after the totals have been determined.
29.14Write an application that reads a line of text, tokenizes the line using space characters as delimiters and outputs only those words beginning with the letter "b".
29.15Write an application that reads a line of text, tokenizes it using space characters as delimiters and outputs only those words ending with the letters "ED".
29.16Write an application that inputs an integer code for a character and displays the corresponding character. Modify this application so that it generates all possible threedigit codes in the range from 000 to 255 and attempts to print the corresponding characters.
29.17Write your own versions of String search methods indexOf and lastIndexOf.
29.18Write an application that reads a five-letter word from the user and produces every possible three-letter string that can be derived from the letters of the five-letter word. For example, the three-letter words produced from the word "bathe" include
"ate," "bat," "bet," "tab," "hat," "the" and "tea."
Whether 'tis nobler in the mind to suffer
contain the word "to" three times, the word "be" two times, the word "or" once, and so on. A more interesting (and useful) printout should then be attempted in which the words are sorted alphabetically.
29.20(Printing Dates in Various Formats) Dates are printed in several common formats. Two of the more common formats are
04/25/1955 and April 25, 1955
Write an application that reads a date in the first format and prints it in the second format.
29.21(Check Protection) Computers are frequently employed in check-writing systems, such as payroll and accounts payable applications. There are many strange stories about weekly paychecks being printed (by mistake) for amounts in excess of $1 million. Incorrect amounts are printed by computerized check-writing systems because of human error or machine failure. Systems designers build controls into their systems to prevent such erroneous checks from being issued.
Another serious problem is the intentional alteration of a check amount by someone who plans to cash a check fraudulently. To prevent a dollar amount from being altered, some computerized check-writing systems employ a technique called check protection. Checks designed for imprinting by computer contain a fixed number of spaces in which the computer may print an amount. Suppose a paycheck contains eight blank spaces in which the computer is supposed to print the amount of a weekly paycheck. If the amount is large, then all eight of the spaces will be filled. For example,
[Page 1395]
1,230.60 (check amount)
--------
12345678 (position numbers)
On the other hand, if the amount is less than $1000, then several of the spaces would ordinarily be left blank. For example,
99.87
--------
12345678
contains three blank spaces. If a check is printed with blank spaces, it is easier for someone to alter the amount of the check. To prevent a check from being altered, many check-writing systems insert leading asterisks to protect the amount as follows:
***99.87
--------
12345678
Write an application that inputs a dollar amount to be printed on a check, then prints the amount in check-protected format with leading asterisks if necessary. Assume that nine spaces are available for printing the amount.
29.22(Writing the Word Equivalent of a Check Amount) Continuing the discussion in Exercise 29.21, we reiterate the importance of designing check-writing systems to prevent alteration of check amounts. One common security method requires that the check amount be written in numbers and spelled out in words as well. Even if someone is able to alter the numerical amount of the check, it is extremely difficult to
change the amount in words. Write an application that inputs a numeric check amount and writes the word equivalent of the amount. For example, the amount 112.43 should be written as
ONE hundred TWELVE and 43/100
29.23(Morse Code) Perhaps the most famous of all coding schemes is the Morse code, developed by SamuelMorse in 1832 for use with the telegraph system. The Morse code assigns a series of dots and dashes to each letter of the alphabet, each digit, and a few special characters (e.g., period, comma, colon, semicolon). In soundoriented systems, the dot represents a short sound and the dash represents a long sound. Other representations of dots and dashes are used with light-oriented systems and signal-flag systems. Separation between words is indicated by a space or, simply, the absence of a dot or dash. In a sound-oriented system, a space is indicated by a short time during which no sound is transmitted. The international version of the Morse code appears in Fig. 29.26.
Figure 29.26. The letters of the alphabet as expressed in international Morse code.
(This item is displayed on page 1396 in the print version)
Character |
Code |
Character |
Code |
|
|
|
|
|
|
A |
.- |
T |
- |
|
B |
-... |
U |
..- |
|
C |
-.-. |
V |
...- |
|
D |
-.. |
W |
.-- |
|
E |
. |
X |
-..- |
|
F |
..-. |
Y |
-.-- |
|
G |
--. |
Z |
--.. |
|
H |
.... |
|
|
|
|
|
|
||
I |
.. |
Digits |
|
|
J |
.--- |
1 |
.---- |
|
|
||||
K |
-.- |
2 |
..--- |
|
L |
.-.. |
3 |
...-- |
|
M |
-- |
4 |
....- |
|
N |
-. |
5 |
..... |
|
O |
--- |
6 |
-.... |
|
P |
.--. |
7 |
--... |
|
Q |
--.- |
8 |
---.. |
|
R |
.-. |
9 |
----. |
|
S |
... |
0 |
----- |
|
|
|
|
|
|
Write an application that reads an English-language phrase and encodes it into Morse code. Also write an application that reads a phrase in Morse code and converts it into the English-language equivalent. Use one blank between each Morse-coded letter and three blanks between each Morse-coded word.
29.24(Metric Conversion Application) Write an application that will assist the user with metric conversions. Your application should allow the user to specify the names of the units as strings (i.e., centimeters, liters, grams, etc., for the metric system and inches, quarts, pounds, etc., for the English system) and should respond to simple questions, such as
"How many inches are in 2 meters?" "How many liters are in 10 quarts?"
Your application should recognize invalid conversions. For example, the question
"How many feet are in 5 kilograms?"
is not meaningful because "feet" is a unit of length, whereas "kilograms" is a unit of mass.
[Page 1396]
Special Section: Challenging String-Manipulation Projects
29.25(Project: A Spelling Checker) Many popular word-processing software packages have built-in spell checkers. In this project, you are asked to develop your own spellchecker utility. We make suggestions to help get you started. You should then consider adding more capabilities. Use a computerized dictionary (if you have access to one) as a source of words.
Why do we type so many words with incorrect spellings? In some cases, it is because we simply do not know the correct spelling, so we make a best guess. In some cases, it is because we transpose two letters (e.g., "defualt" instead of "default"). Sometimes we double-type a letter accidentally (e.g., "hanndy" instead of "handy"). Sometimes we type a nearby key instead of the one we intended (e.g., "biryhday" instead of "birthday"), and so on.
Design and implement a spell-checker application in Java. Your application should maintain an array wordList of strings. Enable the user to enter these strings. [Note: In Chapter 14, we have introduced file processing. With this capability, you can obtain the words for the spell checker from a computerized dictionary stored in a file.]
Your application should ask a user to enter a word. The application should then look up that word in the wordList array. If the word is in the array, your application should print "Word is spelled correctly." If the word is not in the array, your application should print "word is not spelled correctly." Then your application should try to locate other words in wordList that might be the word the user intended to type. For example, you can try all possible single transpositions of adjacent letters to discover that the word "default" is a direct match to a word in wordList. Of course, this implies that your application will check all other single transpositions, such as "edfault," "dfeault," "deafult," "defalut" and "defautl." When you find a new word that matches one in wordList, print it in a message, such as
[Page 1397]
Did you mean "default"?
Implement other tests, such as replacing each double letter with a single letter, and any other tests you can develop to improve the value of your spell checker.
29.26(Project: A Crossword Puzzle Generator) Most people have worked a crossword puzzle, but few have ever attempted to generate one. Generating a crossword puzzle is suggested here as a string-manipulation project requiring substantial sophistication and effort.
There are many issues the programmer must resolve to get even the simplest crossword-puzzle-generator application working. For example, how do you represent the grid of a crossword puzzle inside the computer? Should you use a series of strings or two-dimensional arrays?
The programmer needs a source of words (i.e., a computerized dictionary) that can be directly referenced by the application. In what form should these words be stored to facilitate the complex manipulations required by the application?
If you are really ambitious, you will want to generate the clues portion of the puzzle, in which the brief hints for each across word and each down word are printed. Merely printing a version of the blank puzzle itself is not a simple problem.
