[SOLVED] A good way to compress nested "if else" statements?

I concur with @bryan and @scudly that a lookup table is probably the best solution here.

Although for the example cases a little reorganization can simplify things somewhat. If you always check the last two characters, then you can test the length, then extract the last two characters, check the first with if/elseif and nest switch statements. It’s not vastly different, but adds less if/elseif visual mess and so is potentialyl slightly more readable.

String str = "vlad";

if( str.length() >= 2) {
    final char one = str.charAt( str.length() - 2 );
    final char two = str.charAt( str.length() - 1 );
    
    if( one == 'a' ) {
        switch(two) {
            case 'a': break;
            case 'b': break;
            case 'c': break;
            case 'd': break;
            default:   break;
        }
    }
}

As an addendum though, if anyone is still wondering, Java does support String “constants” for switch cases as of Java/JDK 7 (aka 1.7). Also, although Java String variables are technically immutable, you must either use final variables or quoted strings (e.g. “testcase”) because they are re-assignable.

Taking advantage of that, a more straightforward switch block can be devised.

switch(test) {
    case "aa": doStuff(); break;
    case "ab": doStuff(); break;
    case "ac": doStuff(); break;
    case "ad": doStuff(); break;
    //....
    default:      break;
}
2 Likes