user3517441 user3517441 - 3 months ago 7
Java Question

If/Else alternative

public boolean typeMatch(char c1, char c2) {

if (c1 == '{' || c1 == '}') {
return (c2 == '{' || c2 == '}');
} else if (c1 == '(' || c1 == ')') {
return (c2 == '(' || c2 == ')');
} else if (c1 == '[' || c1 == ']') {
return (c2 == '[' || c2 == ']');
} else {
return false;
}
}


I have the above code in my program and I was wondering if there is a better way to implement this method without using a lot of if/else statements.

Answer

You could extract your symbol pairs (open and close) into a char[][], and then loop through that array to test for matches. Something like,

static final char[][] pairs = { { '{', '}' }, { '(', ')' }, { '[', ']' } };

public boolean typeMatch(char c1, char c2) {
    for (char[] pair : pairs) {
        if (c1 == pair[0] || c1 == pair[1]) {
            return c2 == pair[0] || c2 == pair[1];
        }
    }
    return false;
}
Comments