An Example: String Processing

In this lesson, we will debug a program that extracts delimited words from a string.

Background remarks

The following Boolean expression:

(response != 'N') || (response != 'n')

is always true. If the char variable response contains 'n', the expression response != 'N' is true, so the entire expression is true. If response contains 'N', the expression response != 'n' is true, which makes the entire expression true. A while loop or a do loop controlled by this expression would be infinite.

One way to correct such a loop is to change the operator || in the previous Boolean expression to &&. That is, we can change the expression to:

(response != 'N') && (response != 'n')

Now the loop cycles as long as response contains any character other than 'N' or 'n'.

Avoid negative thinking

A less error-prone way to write this loop is to avoid thinking negatively. As written, the loop cycles as long as response does not contain the particular values 'N' or 'n'. Why not cycle as long as response does contain other particular values, namely 'Y' or 'y'? That is, a loop of the form

do
{
   .
   .
   .
} while ((response == 'Y') || (response == 'y'));

is not only correct, but also easier to understand. Thus, we are more likely to avoid a logical error. Realize, however, that if we only know the values that a variable cannot contain, we might have to think negatively. Such is the case for the example we are about to consider in this lesson.

Finding words in a string

Imagine that Jill is asked to write a Java class to identify the words in a given string that are separated by either a comma or a slash. For example, the string might be:

bug,buffalo,cat/dog,eagle

Although Jill could use the class Scanner, as we discussed in an earlier chapter, she used a loop instead. The program given below contains Jill’s initial attempt.

Get hands-on with 1400+ tech skills courses.