go to previous page   go to home page   go to next page highlighting

Answer:

There is nothing wrong with the program. Since color is a primitive data type, an expression such as

color == 'V'

compares the contents of color (a character) to the character literal 'V'. However, the following is wrong:

color == "V"

This is asking to compare the primitive character value in color with a reference to the String object "V".


Range Testing

Say that you have the following problem: Assign a Beaufort number to bNumber based on wind speed in meters per second.

wind speed Beaufort number
0 - 0.3 0
0.3 - 1.6 1
1.6 - 3.4 2
3.4 - 5.5 3
5.5 - 8.0 4
8.0 - 10.8 5
10.8 - 13.9 6
13.9 - 17.2 7
17.2 - 20.8 8
20.8 - 24.5 9
24.5 - 28.5 10
28.5 - 32.7 11
>=32.7 12

Assume that the upper number in each range is not included.

Lots of cases! You would hope that the switch statement would work for this. But it does not. Floating point values don't work with switch statements. You need to use if and else if.

if      ( speed <  0.3 ) bNumber = 0;
else if ( speed <  1.6 ) bNumber = 1;
else if ( speed <  3.4 ) bNumber = 2;
else if ( speed <  5.5 ) bNumber = 3;
else if ( speed <  8.0 ) bNumber = 4;
else if ( speed < 10.8 ) bNumber = 5;
else if ( speed < 13.9 ) bNumber = 6;
else if ( speed < 17.2 ) bNumber = 7;
else if ( speed < 20.8 ) bNumber = 8;
else if ( speed < 24.5 ) bNumber = 9;
else if ( speed < 28.5 ) bNumber = 10;
else if ( speed < 32.7 ) bNumber = 11;
else                     bNumber = 12;

QUESTION 13:

Could integer ranges be used with a switch statement? Say that value is expected to be in the range 1..10 and you want three categories: 1 to 3, 4 to 7, 8 to 10.


go to previous page   go to home page   go to next page