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 lowercase. The calling string remains unchanged. To fix the error, we can assign
the lowercase string back to the original string with
s = s.toLowerCase( );
However, we are 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 ;
}
Search WWH ::




Custom Search