I suggest making the code easier to maintain by storing the bracket pairs in
private static final char[] opening = new char[]{'(', '[', '{'};
private static final char[] closing = new char[]{')', ']', '}'};
then make a utility function wich gives you the matching index
private static int getOpenCode(char c)
private static int getCloseCode(char c)
both should return some -1 for not found and the index if found. Finally you can store the bracketing as a
Stack<Integer>
with codes corresponding to indices. The logic would change to
protected int checkBrackets(String input) {
// ...
if (getOpenCode(individualChar) != -1) { // Opening bracket
theStack.push(getOpenCode(individualChar));
} else if (getCloseCode(individualChar) != -1) { // Closing bracket
if (theStack.isEmpty() || theStack.pop() != getCloseCode(individualChar)) return -1; // Unbalanced
}
// ...
if (!theStack.isEmpty()) return -2; // Unclosed
return 0; // Okay
}
Note we are using an int return code instead of stdout so that the executing code can decide on how to report. You may also return a different code wich contains the erroneous index. The nice thing about this approach is its extensibility: If you want to support a new type of brackets, just append them to the static arrays.