Title: An Introduction to Java Programming and Object-Oriented Application Development
1An Introduction to Java Programming and
Object-Oriented Application Development
- Chapter 7
- Characters, Strings, and Formatting
2Objectives
- In this chapter you will
- Use the Character wrapper class to work with
characters - Employ several methods of the Character class
- Explore how to manipulate strings using the
StringBuilder class - Use the StringTokenizer class to break strings
into tokens - Perform sophisticated string formatting using the
printf and format methods
3Working with Characters
- Recall char and String from Chapter 2
- Recall the String class methods equals and
substring from Chapter 5 - Brief review of the char data type
- Methods in the Character class
4Brief Review of the char Data Type
- Recall a char is one of eight primitive types
- A character is any symbol represented by Unicode
- Always expressed inside single quotes
- Every individual character has an equivalent
integer value - The methods of the Character class manipulate
characters
5Brief Review of the char Data Type (continued)
6Methods in the Character Class
- The Character class is a wrapper class
- The Integer and Double classes are also wrapper
classes - Each primitive type has a corresponding wrapper
class - A wrapper class holds the value of a primitive
type within an object so methods can be applied
7Methods in the Character Class (continued)
- charValue retrieves the character stored in the
Character object - compareTo returns the difference in Unicode
values for two characters - equals is true if two characters are identical
- isDigit is true if a character is in 0-9
- isLetter is true if a character is in a-z or A-Z
8Methods in the Character Class (continued)
- isWhiteSpace is true if the character is a space
- isWhiteSpace returns false if the character is
newline, tab, etc. - toLowerCase changes uppercase to lowercase
- toUpperCase changes lowercase to uppercase
9Apply the Concept
- Develop an application to check the validity of a
password - Must be between 8 and 15 characters in length
- May not contain spaces
- Must contain at least one nonnumeric uppercase
character and one nonnumeric lowercase character - Must contain at least one numeric digit
10Apply the Concept (continued)
- Several boolean variables track whether the
password is valid - The number of characters is determined with
length from the String class - A loop examines each character
- Uses the charAt method to extract each character
- Tested using isWhiteSpace, isDigit, isLowerCase,
isUpperCase
11Apply the Concept (continued)
- If the appropriate character is found, boolean
variable set to true - Errors appended to an error message
- An ifelse statement tests if the password is
valid (i.e. all booleans set appropriately) - Either the error message is displayed, or a
message saying the password is valid
12Apply the Concept (continued)
- if statements test each validity rule
- Each if statement tests for a required character
- In the case of white space, a prohibited
character - If the character is found and it is the first one
- if statement is executed
- flag is set to true
- If the character is found and it is not the
first, the statement is skipped - Programs using Boolean logic are prone to error
and must be extensively tested
13Apply the Concept (continued)
14Working with Strings
- Coming next
- Brief review of the String class
- The StringBuilder class
- The StringTokenizer class
15Brief Review of the String Class
- Recall a string is an object
- String myStr Johnson
- String myStr new String(Johnson)
- Recall the methods equals, length and substring
- A string is a reference variable that contains
the memory address of an array of characters - Two classes StringBuilder and StringTokenizer
manipulate strings
16Brief Review of the String Class (continued)
- StringBuilder provides methods to manipulate and
build strings - StringTokenizer breaks strings into tokens
- A token is a group of characters within a string
- Tokens are separated by delimiters
- The tokens in this sentence are delimited by
white space
17The StringBuilder Class
- A String object is immutable
- Once created it can never be changed
- StringBuilder allows strings to be modified
- StringBuilder is in java.lang
- All methods in StringBuilder are nonstatic
18The StringBuilder Class (continued)
- append adds text to an existing StringBuilder
object - insert inserts a second argument just after the
position given by the first argument - deleteCharAt deletes a single character from a
StringBuilder at a given position - replace replaces all occurrences of one character
with another - toString creates a string that contains the data
from the StringBuilder object
19The StringTokenizer Class
- StringTokenizer is in java.util
- Breaks a string into tokens
- Create the string to be tokenized
- Create the StringTokenizer object linked to the
string - Apply the StringTokenizer object to the string to
get a token - nextToken and countTokens are nonstatic
20Apply the Concept
- Develop an application that takes a name and a
Social Security number and reformats them - Test the input to determine if it is acceptable
- Data is reformatted
- Name reformatted to print the last name first
- Hyphens removed from Social Security number
- Application is broken into methods
21Apply the Concept (continued)
- Four method calls follow the variable declaration
- getName gets the name from the user
- getSsn gets the SSN from the user
- createOutputName formats the name
- createOutputSsn formats the SSN
- main method concludes with the display of the
output
22Apply the Concept (continued)
- getName and getSsn are similar
- nameTokenizer in getName is a different memory
address than nameTokenizer in main - Both nameTokenizer variables contain a reference
to the same StringTokenizer object - nameTokenizer is instantiated using the input
string - An if statement tests for 3 tokens
23Apply the Concept (continued)
- A dowhile loop repeats and prompts the user for
correct input - getName returns to main when the dowhile loop
terminates - The method createOutputName extracts first,
middle, and last names, and stores them in an
array - The name array is appended to a StringBuilder
object - The StringBuilder is converted to a string and
returned to main
24Apply the Concept (continued)
25Formatting Data for Output
- Output to the terminal with System.out.print and
System.out.println - Output to a GUI window using JOptionPane.showMessa
geDialog - Formatting with ( ) and NumberFormat
- Next printf in the PrintStream class in java.io
- format in the Formatter class in java.util
26The printf and format Methods
- We have been using System.out.println and string
concatenation ( ) - Instead of print and println, use printf and
format
27The printf and format Methods (continued)
28The printf and format Methods (continued)
29The printf and format Methods (continued)
- printf takes a format string and a string
variable printf(Cost .2f\n, cost ) - The format specifier begins with , ends with a
conversion character .2f - Conversion suffix characters may follow the
conversion characters - Integers use conversion characters d and x
- Floating points use conversion characters e, E,
f, and g
30The printf and format Methods (continued)
- Characters and strings use the conversion
characters C and S - Dates and times use the conversion character t,
possibly with suffix characters C, A, B, d, Y - The argument index specifies the argument to
which the format specifier applies - 1 is the first, 2 is the second,, n is the
nth - The field width is the number of spaces an
argument occupies - The precision is the number of decimal places
31The format Method
- The printf method displays to the command window
- printf cannot be used to output to a GUI or file
- The format method in the Formatter class can
output to a GUI or file - format is identical to printf
32The format Method (continued)
33Case Study MusicWorld
- Recall MusicWorld allows a user to input titles
of CDs for purchase - The total, including quantity discount and tax,
is displayed at the end - Eventually, the purchase information will be
stored in a database - Information in a database must be associated with
a unique identifier - Use date and time to create an order identifier
34Flowcharts for New Features of MusicWorldApp7.java
New variables are added Old variables are removed
35Flowcharts for New Features of MusicWorldApp7.java
(continued)
- The method displayOrderID uses the current time
and date to create a unique order ID - The main method calls displayOrderOutput
- The method displayOrderOutput calls the method
createOrderID - The method createOrderID performs the majority of
the formatting - The identifier is in the form YYMMDDHHMMSS
36Program Code for MusicWorldApp7.java
- The only changes from MusicWorldApp6.java are in
three methods - displayItemOutput
- displayOrderOutput
- createOrderID
- Each method will be discussed next
37The displayItemOutput Method
- Line 147 is the format string to be used in
printf s\n\nss\nss\ns.2f\nsd\ns.2f\
n\ns.2f\n\ns - There must be exactly one argument for every
format specifier - The first s corresponds to the variable
headerStr - The second s corresponds to the literal CD ID
38The displayOrderOutput Method
- Lines 184-185 create a DateFormat object
- The argument Locale.FRENCH causes the date to be
in the format YY/DD/MM and time to be in 24-hour
format - createOrderID is called, and returns the order ID
- The order ID is appended to a StringBuilder
- The StringBuilder is converted to a string and
displayed to the console
39The createOrderID Method
- A StringBuilder object is instantiated
- Methods of the StringBuilder class are used to
delete and rearrange its parts - The StringBuilder object is created to a string
and returned to displayOrderID - In Chapter 9, the program will write the
information to a file
40Summary
- Characters are represented by Unicode values
- The Character class is a wrapper class for
characters - All primitive types have wrapper classes to allow
methods to act upon the primitive value - StringBuilder allows strings to be manipulated
- StringTokenizer breaks strings into tokens
separated by delimiters
41Summary (continued)
- All methods in StringBuilder and StringTokenizer
are nonstatic - The method printf is in the class PrintStream and
formats strings - The method format is in the class Formatter and
operates identically to printf - The method format can direct formatting to a GUI
window or a file