Java Algorithms Bracket Checker
import java.util.Stack; class BracketChecker { private String input; // input string public BracketChecker(String in) // constructor {/* ww w . jav a2s .co m*/ input = in; } public void check() { Stack<Character> theStack = new Stack<>(); // make stack for (int j = 0; j < input.length(); j++) // get chars in turn { char ch = input.charAt(j); // get char switch (ch) { case '{': // opening symbols case '[': case '(': theStack.push(ch); // push them break; case '}': // closing symbols case ']': case ')': if (!theStack.isEmpty()) { char chx = theStack.pop(); // pop and check if ((ch == '}' && chx != '{') || (ch == ']' && chx != '[') || (ch == ')' && chx != '(')) System.out.println("Error: " + ch + " at " + j); } else // prematurely empty System.out.println("Error: " + ch + " at " + j); break; default: // no action on other characters break; } } if (!theStack.isEmpty()) System.out.println("Error: missing right delimiter"); else { System.out.println("no error"); } } } public class Main { public static void main(String[] args) { BracketChecker theChecker = new BracketChecker("(a+b)+{(4+5)+r[1]+a()}") ; theChecker.check(); // check brackets } }