Source of BalanceChecker.java


  1: //Note: We are using the class LinkedStack instead of 
  2: //      the class OurStack that the book uses.
  3: /**
  4:    A class that checks whether the parentheses, brackets, and braces 
  5:    in a string occur in left/right pairs.
  6:    @author Frank M. Carrano, Timothy M. Henry
  7:    @version 5.0 */
  8: public class BalanceChecker
  9: {
 10:    /** Decides whether the parentheses, brackets, and braces 
 11:        in a string occur in left/right pairs.
 12:        @param expression  A string to be checked.
 13:        @return  True if the delimiters are paired correctly. */
 14:    public static boolean checkBalance(String expression)
 15:    {
 16:       StackInterface<Character> openDelimiterStack = new LinkedStack<>();

 18:       int characterCount = expression.length();
 19:       boolean isBalanced = true;
 20:       int index = 0;
 21:       char nextCharacter = ' ';
 22:        
 23:       while (isBalanced && (index < characterCount))
 24:       {
 25:          nextCharacter = expression.charAt(index);
 26:          switch (nextCharacter)
 27:          {
 28:             case '(': case '[': case '{':
 29:                openDelimiterStack.push(nextCharacter);
 30:                break;             
 31:             case ')': case ']': case '}':
 32:                if (openDelimiterStack.isEmpty())
 33:                   isBalanced = false;
 34:                else
 35:                {
 36:                   char openDelimiter = openDelimiterStack.pop();
 37:                   isBalanced = isPaired(openDelimiter, nextCharacter);
 38:                } // end if
 39:                break;
 40:             default: break; // Ignore unexpected characters
 41:          } // end switch
 42:          index++;
 43:       } // end while
 44:        
 45:       if (!openDelimiterStack.isEmpty())
 46:          isBalanced = false;
 47:          
 48:       return isBalanced;
 49:    } // end checkBalance
 50:   
 51:    // Returns true if the given characters, open and close, form a pair
 52:    // of parentheses, brackets, or braces.
 53:    private static boolean isPaired(char open, char close)
 54:    {
 55:       return (open == '(' && close == ')') ||
 56:              (open == '[' && close == ']') ||
 57:              (open == '{' && close == '}');
 58:    } // end isPaired
 59: } // end BalanceChecker