Java Switch Statement - Is "or"/"and" possible?

GlassZee picture GlassZee · Mar 27, 2012 · Viewed 103.3k times · Source

I implemented a font system that finds out which letter to use via char switch statements. There are only capital letters in my font image. I need to make it so that, for example, 'a' and 'A' both have the same output. Instead of having 2x the amount of cases, could it be something like the following:

char c;

switch(c){
case 'a' & 'A': /*get the 'A' image*/; break;
case 'b' & 'B': /*get the 'B' image*/; break;
...
case 'z' & 'Z': /*get the 'Z' image*/; break;
}

Is this possible in java?

Answer

Matt Ball picture Matt Ball · Mar 27, 2012

You can use switch-case fall through by omitting the break; statement.

char c = /* whatever */;

switch(c) {
    case 'a':
    case 'A':
        //get the 'A' image;
        break;
    case 'b':
    case 'B':
        //get the 'B' image;
        break;
    // (...)
    case 'z':
    case 'Z':
        //get the 'Z' image;
        break;
}

...or you could just normalize to lower case or upper case before switching.

char c = Character.toUpperCase(/* whatever */);

switch(c) {
    case 'A':
        //get the 'A' image;
        break;
    case 'B':
        //get the 'B' image;
        break;
    // (...)
    case 'Z':
        //get the 'Z' image;
        break;
}