Chapter 3: Program Statements

Download Report

Transcript Chapter 3: Program Statements

Infinite Loops
 The body of a while loop eventually must make the
condition false
 If not, it is an infinite loop, which will execute until the
user interrupts the program
 This is a common logical error
 You should always double check to ensure that your
loops will terminate normally
 See Forever.java (page 165)
1
Nested Loops
 Similar to nested if statements, loops can be nested as
well
 That is, the body of a loop can contain another loop
 Each time through the outer loop, the inner loop goes
through its full set of iterations
 See PalindromeTester.java (page 167)
The StringTokenizer Class
 The elements that comprise a string are referred to as
tokens
 The process of extracting these elements is called
tokenizing
 Characters that separate one token from another are
called delimiters
 The StringTokenizer class, which is defined in the
java.util package, is used to separate a string into
tokens
The StringTokenizer Class
 The default delimiters are space, tab, carriage return, and
the new line characters
 The nextToken method returns the next token
(substring) from the string
 The hasMoreTokens returns a boolean indicating if
there are more tokens to process
 See CountWords.java (page 172)
Choosing a Loop Structure
 When you can’t determine how many times you want to
execute the loop body, use a while statement or a do
statement
• If it might be zero or more times, use a while statement
• If it will be at least once, use a do statement
 If you can determine how many times you want to
execute the loop body, use a for statement