title: using stacks to check for matching brackets in java
body: <p>hi guys I am trying to create a program to allow a user to input a sequence of brackets (one at a time) and check to see whether there is a corresponding ending bracket. The brackets are entered on a new line every time to aid in the reading. I've set up an ADT for it but just cant think of how to get the while loop going and the checking...... I know if an ( bracket is entered i should push that into the stack and when a ( is entered i should pop one of the stack but I just cant work out the bits in the middle any help would be loved :)</p>
  
  <pre><code>//main code   
  import java.util.*;
  
  public class SameBrackets
  {
     public static void main(String[] args)
     {
        Stack bracket = new Stack();
        Scanner kybd = new Scanner(System.in);
  
        System.out.print("Enter bracket &gt; ");
        String bracketentered = kybd.next();
  
  
            if ("(".equals(bracketentered) )
            {
                   bracket.push(bracketentered);
                   System.out.println(") needed");
            }
            else if (")".equals(bracketentered))
            {
                bracket.pop();
                System.out.println("( needed");
            }
  
  
        }
    }
  </code></pre>
  
  <p>//ADT code</p>
  
  <pre><code>public class Stack
  {
      private String[] a;         //String array
      private int top;
  
      public Stack()
      {
         a = new String[1];           //create String array
         top = 0;                      
      }
  
      public boolean isEmpty()
      {
           return top == 0;
      }
  
      public String pop()          //pop String element
      {
          top--;
          return(a[top]);         //underflow not protected
      }
  
      public void push(String x)      //push String element
      {
          if (top == a.length)
          {
              resize();
          }
          a[top] = x;
          top++;
      }  
  
      private void resize()
      {
          String[] temp = new String[a.length * 2];   //resize String array
          for (int i = 0; i &lt; a.length; i++)
          {
              temp[i] = a[i];
           }
          a = temp;
      }
  }
  </code></pre>