Java Reference
In-Depth Information
EXAMPLE: (continued)
This forces the loop to exit if 'a' or 'b' is entered, and it will make the program
work. Unfortunately, the result is a coding atrocity that should be avoided at all
costs. This “quick fix” does not address the root cause of the error—only the symp-
toms. Moreover, such patches usually won't work for new cases. This particular fix
also results in inconsistent code because the expression ((c!='a') || (c!='b'))
becomes meaningless when we already handle the 'a' and 'b' with the if and break
statements.
To really find the bug, we can turn again to tracing, this time focusing on the Bool-
ean values that control the do-while loop:
do
{
System.out.println("Enter 'A' for option A or 'B' for option B.");
s = keyboard.next( );
s = s.toLowerCase( );
c = s.charAt(0);
System.out.println("c != 'a' is " + (c != 'a'));
System.out.println("c != 'b' is " + (c != 'b'));
System.out.println("(c != 'a') || (c != 'b')) is "
+ ((c != 'a') || (c != 'b')));
}
while ((c != 'a') || (c != 'b'));
The sample output is now as follows:
Enter 'A' for option A or 'B' for option B.
A
c != 'a' is false
c != 'b' is true
(c != 'a') || (c != 'b')) is true
Since c equals 'a' , the statement (c != 'a') evaluates to false and the statement (c
!= 'b') evaluates to true . When combined, (false || true) is true , which makes
the loop repeat. In spoken English it sounds like “c not equal to 'a' or “c not equal
to 'b'” is a correct condition to repeat the loop. After all, if the character typed in is
not 'a' or the character typed in is not 'b', then the user should be prompted to try
again. Logically however, if (c != 'a') is false (i.e., the character is 'a' ), then (c
!= 'b') must be true. A character cannot make both expressions false , so the final
Boolean condition will always be true . The solution is to replace the “or” with an
“and” so that the loop repeats only if (c != 'a') && (c != 'b')) . This makes the
loop repeat as long as the input character is not 'a' and it is not 'b' .
(continued)
Search WWH ::




Custom Search