Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are these duplicate cases?

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; 
}
like image 382
lampwins Avatar asked Nov 18 '25 06:11

lampwins


2 Answers

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
like image 174
Christian Ternus Avatar answered Nov 20 '25 19:11

Christian Ternus


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.

  • this is why the compiler complains

Read the switch tutorial to see how fallthrough is used

like image 39
Reimeus Avatar answered Nov 20 '25 21:11

Reimeus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!