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 (page 165)
Nested Loops
 Similar to nested if statements, loops can be nested as
 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 (page 167)
The StringTokenizer Class
 The elements that comprise a string are referred to as
 The process of extracting these elements is called
 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
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 (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
• 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