1 import java.util.Stack; 2 import javax.swing.JOptionPane; 3 4 /** Check for balanced parentheses. */ 5 6 public class AdvancedParenChecker 7 { 8 // Constants for target characters 9 private static final String kOpen = "([{"; 10 private static final String kClose = ")]}"; 11 12 /** Test the input string to see that it contains balanced parentheses. 13 @param expression A String containing the expression to be examined 14 @return true if all the parentheses match 15 */ 16 public static boolean isBalanced(String expression) 17 { 18 Stack stack = new Stack(); // Create an empty stack. 19 boolean balanced; 20 try 21 { 22 // Consider all the characters in the expression 23 int index = 0; 24 while (index < expression.length() && balanced) 25 { 26 char nextCh = expression.charAt(index); 27 // Push any open paren 28 if (kOpen.indexOf(nextCh) > 0) 29 { 30 stack.push(nextCh); 31 } 32 // Pop any close paren 33 else if (kClose.indexOf(nextCh) > 0) 34 { 35 char topCh = stack.pop(); 36 balanced = kOpen.indexOf(topCh) 37 == kClose.indexOf(nextCh); 38 } 39 index++; 40 } 41 } 42 catch (EmptyStackException ex) 43 { 44 // We know it's unbalanced 45 balanced = false 46 } 47 // Did all parens match? 48 return (balanced && stack.empty()); 49 }