Java Reference
In-Depth Information
EXAMPLE: (continued)
At this point we could employ tracing to try to locate the source of the error. Here
is the code with output statements inserted:
do
{
System.out.println("Enter 'A' for option A or 'B' for option B.");
s = keyboard.next( );
System.out.println("String s = " + s);
s.toLowerCase( );
System.out.println("Lowercase s = " + s);
c = s.charAt(0);
System.out.println("c = " + c);
}
while ((c != 'a') || (c != 'b'));
Sample output is as follows:
Enter 'A' for option A or 'B' for option B.
A
String s = A
Lowercase s = A
c = A
Enter 'A' for option A or 'B' for option B.
The println statements make it clear what is wrong—the string s does not change to
lowercase. A review of the toLowerCase( ) documentation reveals that this method
does not change the calling string, but instead returns a new string converted to lower-
case. The calling string remains unchanged. To fix the error, we can assign the lower-
case string back to the original string with
s = s.toLowerCase( );
However, we're not done yet. Even after fixing the lowercase error, the program is
still stuck in an infinite loop, even when we enter 'A' or 'B' . A novice programmer
might “patch” the program like so to exit the 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);
if ( c == 'a')
break;
if (c == 'b')
break;
}
while ((c != 'a') || (c != 'b'));
Search WWH ::




Custom Search