/** * CSE 373, Winter 2011, Jessica Miller * This program checks that the parentheses and curly brackets in a String are matching. */ import java.io.FileNotFoundException; import java.util.Stack; public class SymbolsChecker { public static void main(String[] args) throws FileNotFoundException { String test1 = "()"; String test2 = "{}"; String test3 = "{()}"; String test4 = "()(){}{}"; String test5 = "public static void echo(int x) { System.out.print(x) };"; String test6 = "(()"; String test7 = "{}}"; String test8 = "({)}"; String test9 = "public void echo(int x) { System.out.print(x) ;"; System.out.println(test1 + " balanced? " + symbolsMatch(test1)); System.out.println(test2 + " balanced? " + symbolsMatch(test2)); System.out.println(test3 + " balanced? " + symbolsMatch(test3)); System.out.println(test4 + " balanced? " + symbolsMatch(test4)); System.out.println(test5 + " balanced? " + symbolsMatch(test5)); System.out.println(test6 + " balanced? " + symbolsMatch(test6)); System.out.println(test7 + " balanced? " + symbolsMatch(test7)); System.out.println(test8 + " balanced? " + symbolsMatch(test8)); System.out.println(test9 + " balanced? " + symbolsMatch(test9)); } public static boolean symbolsMatch(String str) { Stack symbolsStack = new Stack(); for (int i = 0; i < str.length(); i++) { char nextToken = str.charAt(i); if (nextToken == '{' || nextToken == '(') { symbolsStack.push(nextToken); } else if ((nextToken == '}') && (symbolsStack.isEmpty() || symbolsStack.pop() != '{')) { return false; } else if ((nextToken == ')') && (symbolsStack.isEmpty() || symbolsStack.pop() != '(')) { return false; } } return symbolsStack.isEmpty(); } }