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:    
  7:    @author Frank M. Carrano
  8:    @version 4.0
  9: */
 10: public class BalanceChecker
 11: {
 12:    /** Decides whether the parentheses, brackets, and braces 
 13:        in a string occur in left/right pairs.
 14:        @param expression  A string to be checked.
 15:        @return  True if the delimiters are paired correctly. */
 16:    public static boolean checkBalance(String expression)
 17:    {
 18:       StackInterface<Character> openDelimiterStack = new LinkedStack<>();
 19: 
 20:       int characterCount = expression.length();
 21:       boolean isBalanced = true;
 22:       int index = 0;
 23:       char nextCharacter = ' ';
 24:        
 25:       while (isBalanced && (index < characterCount))
 26:       {
 27:          nextCharacter = expression.charAt(index);
 28:          switch (nextCharacter)
 29:          {
 30:             case '(': case '[': case '{':
 31:                openDelimiterStack.push(nextCharacter);
 32:                break;             
 33:             case ')': case ']': case '}':
 34:                if (openDelimiterStack.isEmpty())
 35:                   isBalanced = false;
 36:                else
 37:                {
 38:                   char openDelimiter = openDelimiterStack.pop();
 39:                   isBalanced = isPaired(openDelimiter, nextCharacter);
 40:                } // end if
 41:                break;
 42:              
 43:             default: break; // Ignore unexpected characters
 44:          } // end switch
 45:          index++;
 46:       } // end while
 47:        
 48:       if (!openDelimiterStack.isEmpty())
 49:          isBalanced = false;
 50:          
 51:       return isBalanced;
 52:    } // end checkBalance
 53:   
 54:    // Returns true if the given characters, open and close, form a pair
 55:    // of parentheses, brackets, or braces.
 56:    private static boolean isPaired(char open, char close)
 57:    {
 58:       return (open == '(' && close == ')') ||
 59:              (open == '[' && close == ']') ||
 60:              (open == '{' && close == '}');
 61:    } // end isPaired
 62: } // end BalanceChecker