Question

For unknown reason I've got a duplicate case label error just in two case blocks in this method. This also appears when I separate cases in every single letter (splashing error on 'O' char). Is it possible to fix it without changing the letters to lower case?

Szyferka(String szyfr){
    char []buf = szyfr.toCharArray();
    int len=szyfr.length();
    for(int i=0; i<len; i++){
        switch(buf[i]){
            case 'A' | 'B' | 'C': buf[i]='2';
            case 'D' | 'E' | 'F': buf[i]='3';
            case 'G' | 'H' | 'I': buf[i]='4';
            case 'J' | 'K' | 'L': buf[i]='5'; //duplicate case label
            case 'M' | 'N' | 'O': buf[i]='6'; //duplicate case label
            case 'P' | 'Q' | 'R' | 'S': buf[i]='7';
            case 'T' | 'U' | 'V': buf[i]='8';
            case 'W' | 'X' | 'Y' | 'Z': buf[i]='9';
            case '.': buf[i]='1';
            case ' ': buf[i]='0';
        }
    }
}
Was it helpful?

Solution

The problem is that you're using bitwise | to combine characters - that's not providing multiple cases as I think you expect it to. Instead, it's just taking the Unicode values for the different characters and combining them with a bitwise-OR operation.

This will show you why you're getting the duplicate case error:

System.out.println('G' | 'H' | 'I');
System.out.println('J' | 'K' | 'L');
System.out.println('M' | 'N' | 'O');

All three lines print 79.

You really want:

case 'A': case 'B': case 'C': buf[i]='2'; break;
case 'D': case 'E': case 'F': buf[i]='3'; break;
etc

(I'd personally reformat this too, but that's a different matter. Note the break statements too!)

You might also want to consider a Map<Character, Character> instead of the switch statement.

OTHER TIPS

They are functioning as bitwise operators -

System.out.println("'J' | 'K' | 'L' " + ('J' | 'K' | 'L')); System.out.println("'M' | 'N' | 'O' " + ('M' | 'N' | 'O'));

Output -

'J' | 'K' | 'L' 79 'M' | 'N' | 'O' 79

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top