ParenChecker.java.html

  1  import java.util.Scanner;
  2  import java.util.Stack;
  3  
  4  /**
  5     This program uses a stack to check whether an expression has balanced 
  6     parentheses.
  7  */
  8  public class ParenChecker
  9  {
 10     public static void main(String[] args)
 11     {
 12        Scanner in = new Scanner(System.in);
 13        System.out.print("Enter an expression with { [ ( ) ] }: ");
 14        String expression = in.nextLine();
 15        
 16        Stack<Character> parens = new Stack<Character>();
 17  
 18        for (int i = 0; i < expression.length(); i++)
 19        {
 20           char ch = expression.charAt(i);
 21           if (ch == '(' || ch == '[' || ch == '{')
 22           {
 23              parens.push(ch);
 24           }
 25           else if (ch == ')' || ch == ']' || ch == '}')
 26           {
 27              if (parens.size() == 0)
 28              {
 29                 System.out.println("Not balanced.");
 30                 return;
 31              }
 32              char open = parens.pop();
 33              if (!(open == '(' && ch == ')'
 34                    || open == '[' && ch == ']'
 35                    || open == '{' && ch == '}'))
 36              {
 37                 System.out.println("Not balanced.");
 38                 return;
 39              }
 40           }
 41        }
 42        if (parens.size() == 0) 
 43        { 
 44           System.out.print("Balanced.");
 45        }
 46        else
 47        { 
 48           System.out.print("Not balanced.");
 49        }
 50     }
 51  }