// FILE: IsBalancedDemonstration.java
// This small demonstration program showing the isBalanced method, which uses 
// a stack of characters to determine whether a string has balanced
// parentheses. 

import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.JOptionPane;

class IsBalancedDemonstration
{

   
   public static void main(String[ ] args)
   {
      String expression;
      
      System.out.println("Please type a string containing various kinds");
      System.out.println("of parentheses ( ) { } [ ]. I'll check whether");
      System.out.println("the parentheses are balanced.");

      // do
      //{
      JOptionPane j = new JOptionPane();
         expression = j.showInputDialog("Your String: "); 
         while ( expression != null) {
	    if (isBalanced(expression))
            System.out.println("That is balanced.");
         else
            System.out.println("That is not balanced.");
         expression = j.showInputDialog("Another string?");
	 }
	

      System.out.println("Thanks for that balancing act.");
      System.exit(0);
   }

   public static boolean isBalanced(String expression)
   // Postcondition: A true return value indicates that the parentheses in the
   // given expression are balanced. Otherwise the return value is false.
   // Note that characters other than ( ) { } and [ ] are ignored.
   {
      // Meaningful names for characters
      final char LEFT_NORMAL  = '(';
      final char RIGHT_NORMAL = ')';
      final char LEFT_CURLY   = '{';
      final char RIGHT_CURLY  = '}';
      final char LEFT_SQUARE  = '[';
      final char RIGHT_SQUARE = ']';
      
      Stack store = new Stack( ); // Stack to store left parentheses
      int i;                              // An index into the string
      boolean failed = false;             // Change to true for a mismatch
      
      for (i = 0; !failed && (i < expression.length( )); i++)
      {
         switch (expression.charAt(i))
         {
            case LEFT_NORMAL:
            case LEFT_CURLY:
            case LEFT_SQUARE: 
               store.push(new Character(expression.charAt(i)));
               break;
            case RIGHT_NORMAL:
               if (store.isEmpty( ) || (((Character)store.pop( )).charValue() != LEFT_NORMAL))
                  failed = true;
               break;
            case RIGHT_CURLY:
               if (store.isEmpty( ) || (((Character)store.pop( )).charValue() != LEFT_CURLY))
                  failed = true;
               break;
            case RIGHT_SQUARE:
               if (store.isEmpty( ) || (((Character)store.pop( )).charValue() != LEFT_SQUARE))
                  failed = true;
               break;
         }
      }
      
      return (store.isEmpty( ) && !failed);
   }

 
}


