Java Reference
In-Depth Information
through each string, character by character, until it determines whether the string
is a palindrome.
The variables left and right store the indexes of two characters. They initially
indicate the characters on either end of the string. Each iteration of the inner loop
compares the two characters indicated by left and right . We fall out of the
inner loop when either the characters don't match, meaning the string is not a
palindrome, or when the value of left becomes equal to or greater than the value
of right , which means the entire string has been tested and it is a palindrome.
Note that the following phrases would not be considered palindromes by the
current version of the program:
A man, a plan, a canal, Panama.
Dennis and Edna sinned.
Rise to vote, sir.
Doom an evil deed, liven a mood.
Go hang a salami; I'm a lasagna hog.
These strings fail our current criteria for a palindrome because of the spaces,
punctuation marks, and changes in uppercase and lowercase. However, if these
characteristics were removed or ignored, these strings read the same forward and
backward. Consider how the program could be changed to handle these situa-
tions. These modifications are included as a programming project at the end of
the chapter.
The break and continue Statements
Java includes two statements that affect the processing of conditionals and loops.
When a break statement is executed, the flow of execution transfers immediately
to the statement after the one governing the current flow. For example, if a break
statement is executed within the body of a loop, the execution of the loop is stopped
and the statement following the loop is executed. It “breaks” out of the loop.
In Chapter 6 we'll see that using the break statement is usually necessary when
writing switch statements. However, it is never necessary to use a break state-
ment in a loop. An equivalent loop can always be written without it. Because the
break statement causes program flow to jump from one place to another, using a
break in a loop is not good practice. You can and should avoid using the break
statement in a loop.
A continue statement has a related effect on loop processing. The continue
statement is similar to a break , but the loop condition is evaluated again, and the
loop body is executed again if it is still true. Like the break statement, the continue
statement can always be avoided in a loop, and for the same reasons, it should be.
 
Search WWH ::




Custom Search