import java.util.Scanner; import java.util.Stack; import java.util.EmptyStackException; // bracket matching based on Algorithm on p201 Goodrich & Tamassia public class BrackMatch { public static void main(String args[]) { System.out.println("Enter input tokens separated by spaces"); System.out.println("Terminate input with ^D"); Stack s = new Stack(); Scanner i = new Scanner(System.in); try { while (i.hasNext()) { String b = i.next(); if (openBrac(b)) s.push(b); if (closeBrac(b)) { if (s.empty()) throw new RuntimeException("Unmatched " + b); String c = (String) s.pop(); if (!matchBrac(c, b)) throw new RuntimeException("Mismatched " + c + b); } } if (s.empty()) System.out.println("Brackets are OK"); else throw new RuntimeException("Unmatched " + s.pop()); } catch (RuntimeException e) { System.out.println("Error: " + e); } } //------------------------ helper methods are below ------------------- public static boolean openBrac(String x) { if (x.equals("(") || x.equals("{") || x.equals("[")) return true; return false; } public static boolean closeBrac(String x) { if (x.equals(")") || x.equals("}") || x.equals("]")) return true; return false; } public static boolean matchBrac(String x, String y) { if (x.equals("(") && y.equals(")")) return true; if (x.equals("{") && y.equals("}")) return true; if (x.equals("[") && y.equals("]")) return true; return false; } }