Java Reference
In-Depth Information
EXAMPLE: (continued)
String s = "";
char c = ' ';
Scanner keyboard = new Scanner(System.in);
do
{
System.out.println("Enter 'A' for option A or 'B' for option B.");
s = keyboard.next( );
s.toLowerCase( );
c = s.substring(0,1);
}
while ((c != 'a') || (c != 'b'));
This program generates a syntax error when compiled:
c = s.substring(0,1); : incompatible types
found : java.lang.String
required: char
The intent was to extract the first character from the string entered by the user and check
to see whether it is 'a' or 'b' . The substring(0,1) call returns a String containing the
first character of s , but c is of type char and the types need to match on both sides of the
assignment. If we employ the “guessing” debugging technique, then we might make the
types match by changing the data type of c to String . Such a change will “fix” this error,
but it will cause new errors because the rest of the code treats c like a char . As a result, we
have added even more errors! Before making any change, consider the larger context and
what the effect of the change will be. In this case, the simplest and best fix is to use
c = s.charAt(0)
to retrieve the first character from s instead of retrieving a substring.
At this point we have corrected the syntax error and our program will compile, but it
will still not run correctly. A sample execution is shown below:
Enter 'A' for option A or 'B' for option B.
C
Enter 'A' for option A or 'B' for option B.
B
Enter 'A' for option A or 'B' for option B.
A
Enter 'A' for option A or 'B' for option B.
(Control-C)
The program is stuck in an infinite loop even when we type in a valid choice. The only way
to stop it is to break out of the program (in the sample output by hitting Control-C, but
you may have to use a different method depending on your computing environment).
(continued)
Search WWH ::




Custom Search