AhmadLang / Java, How To Program, 2004
.pdf
[Page 1346 (continued)]
Self-Review Exercises
28.1 Fill in the blanks in each of the following:
a.All input and output is dealt with in the form of __________.
b.The __________ stream is normally connected to the keyboard.
c.The __________stream is normally connected to the computer screen.
d.System.out's __________ method can be used to format text that is displayed on the standard output.
e.The conversion character __________ may be used to output a decimal integer.
[Page 1347]
f.The conversion characters __________ and __________ are used to display integers in octal and hexadecimal form, respectively.
g.The conversion character __________ is used to display a floating-point value in exponential notation.
h.The conversion characters e and f are displayed with __________ digits of precision to the right of the decimal point if no precision is specified.
i.The conversion characters __________ and __________ are used to print strings and characters, respectively.
j. The conversion character __________ and conversion suffix character __________ are used to print time for the 24-hour clock as hour:minute:second.
k.The __________ flag causes output to be left justified in a field.
l.The __________ flag causes values to be displayed with either a plus sign or a minus sign.
m.The argument index __________ corresponds to the second argument in the argument list.
n.Class __________ has the same capability as printf, but allows programmers to print formatted output to various destinations besides the standard output stream.
28.2 Find the error in each of the following and explain how it can be corrected.
a.The following statement should print the character 'c'.
System.out.printf( "%c\n", "c" );
b.The following statement should print 9.375%.
System.out.printf( "%.3f%", 9.375 );
c.The following statement should print the third argument in the argument list.
System.out.printf( "%2$s\n", "Mon", "Tue", "Wed", "Thu", "Fri" );
d.System.out.printf( ""A string in quotes"" );
e.System.out.printf( %d %d, 12, 20 );
f.System.out.printf( "%s\n", 'Richard' );
28.3 Write a statement for each of the following:
a.Print 1234 right justified in a 10 digit field.
b.Print 123.456789 in exponential notation with a sign (+ or -) and 3 digits of precision.
c.Print 100 in octal form preceded by 0.
d.Given a Calendar object calendar, print a date formatted as month/day/year (each with two digits).
e.Given a Calendar object calendar, print a time for the 24-hour clock as hour:minute:second (each with two digits) using argument index and conversion suffix characters for formatting time.
f.Print 3.333333 with a sign (+ or -) in a field of 20 characters with a precision of 3.
[Page 1347 (continued)]
Answers to Self-Review Exercises
28.1 a) Streams. b) Standard input. c) Standard output. d) printf. e) d. f) o, x or X. g) e or E. h) 6. i) s or S, c or C. j) t, T. k) - (minus). l) + (plus). m) 2$. n) Formatter.
28.2 a. Error: Conversion character c expects an argument of primitive type char.
Correction: To print the character 'c', change "c" to 'c'.
b.Error: Trying to print the literal character % without using the format specifier
%%.
Correction: Use %% to print a literal % character.
c.Error: Argument index does not start with 0, e.g., the first argument is 1$. Correction: To print the third argument use 3$.
d.Error: Trying to print the literal character " without using the \" escape sequence.
Correction: Replace each quote in the inner set of quotes with \".
[Page 1348]
e.Error: The format string is not enclosed in double quotes. Correction: Enclose %d %d in double quotes.
f.Error: The string to be printed is enclosed in single quotes.
Correction: Use double quotes instead of single quotes to represent a string.
28.3 a. System.out.printf( "%10d\n", 1234 );
b.System.out.printf( "%+.3e\n", 123.456789 );
c.System.out.printf( "%#o\n", 100 );
d.System.out.printf( "%tD\n", calendar );
e.System.out.printf( "%1$tH:%1$tM:%1$tS\n", calendar );
f.System.out.printf( "%+20.3f\n", 3.333333 );
[Page 1348 (continued)]
Exercises
28.4Write statement(s) for each of the following:
a.Print integer 40000 right justified in a 15-digit field.
b.Print 200 with and without a sign.
c.Print 100 in hexadecimal form preceded by 0x.
d.Print 1.234 with three digits of precision in a nine-digit field with preceding zeros.
28.5Show what is printed by each of the following statements. If a statement is incorrect, indicate why.
a.System.out.printf( "%-10d\n", 10000 );
b.System.out.printf( "%c\n", "This is a string" );
c.System.out.printf( "%8.3f\n", 1024.987654 );
d.System.out.printf( "%#o\n%#X\n", 17, 17 );
e.System.out.printf( "% d\n%+d\n", 1000000, 1000000 );
f.System.out.printf( "%10.2e\n", 444.93738 );
g.System.out.printf( "%d\n", 10.987 );
28.6Find the error(s) in each of the following program segments. Show the corrected statement.
a.System.out.printf( "%s\n", 'Happy Birthday' );
b.System.out.printf( "%c\n", 'Hello' );
c.System.out.printf( "%c\n", "This is a string" );
d.The following statement should print "Bon Voyage" with the double quotes:
System.out.printf( ""%s"", "Bon Voyage" );
e.The following statement should print "Today is Friday":
System.out.printf( "Today is %s\n", "Monday", "Friday" );
f.System.out.printf( 'Enter your name: ' );
g.System.out.printf( %f, 123.456 );
h.The following statement should print the current time in the format
"hh:mm:ss":
Calendar dateTime = Calendar.getInstance();
System.out.printf( "%1$tk:1$%tl:%1$tS\n", dateTime );
28.7(Printing Dates and Times) Write a program that prints dates and times in the following forms:
GMT-05:00 04/30/04 09:55:09 AM
GMT-05:00 April 30 2004 09:55:09 2004-04-30 day-of-the-month:30 2004-04-30 day-of-the-year:121
Fri Apr 30 09:55:09 GMT-05:00 2004
[Page 1349]
[ Note: Depending on your location, you may get the time zone other than GMT05:00.]
28.8Write a program to test the results of printing the integer value 12345 and the floating-point value 1.2345 in various size fields.
28.9(Rounding Numbers) Write a program that prints the value 100.453627 rounded to the nearest digit, tenth, hundredth, thousandth and ten thousandth.
28.10Write a program that inputs a word from the keyboard and determines the length of the word. Print the word using twice the length as the field width.
28.11(Converting Fahrenheit Temperature to Celsius) Write a program that converts integer Fahrenheit temperatures from 0 to 212 degrees to floating-point Celsius temperatures with three digits of precision. Use the formula
celsius = 5.0 / 9.0 * ( fahrenheit - 32 );
to perform the calculation. The output should be printed in two right-justified columns of 10 characters each, and the Celsius temperatures should be preceded by a sign for both positive and negative values.
28.12Write a program to test all the escape sequences in Fig. 28.23. For the escape sequences that move the cursor, print a character before and after the escape sequence so that it is clear where the cursor has moved.
28.13Write a program that uses the conversion character g to output the value 9876.12345. Print the value with precisions ranging from 1 to 9.
[Page 1350]
Chapter 29. Strings, Characters and Regular
Expressions
The chief defect of Henry King Was chewing little bits of string.
Hilaire Belloc
Vigorous writing is concise. A sentence should contain no unnecessary words, a paragraph no unnecessary sentences.
William Strunk, Jr.
I have made this letter longer than usual, because I lack the time to make it short.
Blaise Pascal
OBJECTIVES
In this chapter you will learn:
To create and manipulate immutable character string objects of class String.
To create and manipulates mutable character string objects of class StringBuffer.
To create and manipulate objects of class Character.
To use a StringTokenizer object to break a String object into tokens.
To use regular expressions to validate String data entered into an application.
[Page 1351]
Outline
29.1 Introduction
29.2 Fundamentals of Characters and Strings
29.3 Class String
29.3.1 String Constructors
29.3.2 String Methods length, charAt and getChars
29.3.3 Comparing Strings
29.3.4 Locating Characters and Substrings in Strings
29.3.5 Extracting Substrings from Strings
29.3.6 Concatenating Strings
29.3.7 Miscellaneous String Methods
29.3.8 String Method valueOf
29.4 Class StringBuffer
29.4.1 StringBuffer Constructors
29.4.2 StringBuffer Methods length, capacity, setLength and ensureCapacity
29.4.3 StringBuffer Methods charAt, setCharAt, getChars and reverse
29.4.4 StringBuffer append Methods
29.4.5 StringBuffer Insertion and Deletion Methods
29.5 Class Character
29.6 Class StringTokenizer
29.7 Regular Expressions, Class Pattern and Class Matcher
29.8 Wrap-Up
Summary
Terminology
Self-Review Exercises
Answers to Self-Review Exercises
Exercises
Special Section: Advanced String-Manipulation Exercises
Special Section: Challenging String-Manipulation Projects
[Page 1351 (continued)]
29.1. Introduction
This chapter introduces Java's stringand character-processing capabilities. The techniques discussed here are appropriate for validating program input, displaying information to users and other text-based manipulations. The techniques are also appropriate for developing text editors, word processors, pagelayout software, computerized typesetting systems and other kinds of text-processing software. We have already presented several string-processing capabilities in earlier chapters. This chapter discusses in detail the capabilities of class String, class StringBuffer and class Character from the java.lang package and class StringTokenizer from the java.util package. These classes provide the foundation for string and character manipulation in Java.
The chapter also discusses regular expressions that provide applications with the capability to validate input. The functionality is located in the String class along with classes Matcher and Pattern located in the java.util.regex package.
[Page 1352]
29.2. Fundamentals of Characters and Strings
Characters are the fundamental building blocks of Java source programs. Every program is composed of a sequence of characters thatwhen grouped together meaningfullyare interpreted by the computer as a series of instructions used to accomplish a task. A program may contain character literals. A character literal is an integer value represented as a character in single quotes. For example, 'z' represents the integer value of z, and '\n' represents the integer value of newline. The value of a character literal is the integer value of the character in the Unicode character set. Appendix B presents the integer equivalents of the characters in the ASCII character set, which is a subset of Unicode (discussed in Appendix F). For detailed information on Unicode, visit www.unicode.org.
Recall from Section 2.2 that a string is a sequence of characters treated as a single unit. A string may include letters, digits and various special characters, such as +, -, *, / and $. A string is an object of class String. String literals (stored in memory as String objects) are written as a sequence of characters in double quotation marks, as in:
"John |
Q. Doe" |
(a name) |
|
"9999 |
Main |
Street" |
(a street address) |
"Waltham, |
Massachusetts" |
(a city and state) |
|
"(201) |
555 |
-1212" |
(a telephone number) |
A string may be assigned to a String reference. The declaration
String color = "blue";
initializes String reference color to refer to a String object that contains the string "blue".
Performance Tip 29.1
Java treats all string literals with the same contents as a single
String object that has many references to it. This conserves memory.
