I am trying to convert a phone number that is written in letters, into its true numeric form. I have this switch statement inside of a for loop that looks at each char of the string, but eclipse is saying that I have duplicate cases ('G' | 'H' | 'I', 'J' | 'K' | 'L', 'M' | 'N' | 'O') and I don't understand why?
switch(parts[1].charAt(i)){
case 'A' | 'B' | 'C' : number.concat("2"); break;
case 'D' | 'E' | 'F' : number.concat("3"); break;
case 'G' | 'H' | 'I' : number.concat("4"); break;
case 'J' | 'K' | 'L' : number.concat("5"); break;
case 'M' | 'N' | 'O' : number.concat("6"); break;
case 'P' | 'Q' | 'R' | 'S' : number.concat("7"); break;
case 'T' | 'U' | 'V' : number.concat("8"); break;
case 'W' | 'X' | 'Y' | 'Z' : number.concat("9"); break;
}
Hilariously, I think I know what's going on.
When you do 'A' | 'B', you're doing bitwise-OR on the byte values of A and B. Your IDE is detecting that a few of the resulting values are equivalent. This definitely isn't what you want to do.
What you want is more like:
case 'A':
case 'B':
case 'C':
number.concat("2");
break;
case 'D':
[...]
and so on.
See "SwitchDemo2" at http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html for more info.
Verified (using Python):
>>> ord('G') | ord('H') | ord('I')
79
>>> ord('J') | ord('K') | ord('L')
79
The | character in your code is acting as a bitwise OR operator use switch fallthrough instead
switch(parts[1].charAt(i)){
case 'A':
case 'B':
case 'C':
number.concat("2");
break;
...
Look at the results of these bytevalues
System.out.println('G' | 'H' | 'I');
System.out.println('J' | 'K' | 'L');
both print 79
Quoting from JLS 14.11
No two of the case constant expressions associated with a switch statement may have the same value.
Read the switch tutorial to see how fallthrough is used
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With