Results 1 to 1 of 1
  1. #1
    cjw92 is offline Member
    Join Date
    Feb 2011
    Posts
    11
    Rep Power
    0

    Default Check for Balanced Parenthesis in a Stack

    The problem is: Read in a string representing an expression that contains parentheses and have your program print that string and report whether or not the parentheses are correctly balanced.

    Examples: This input string  this output statement.
    ( a + b ) / 9  ( a + b ) / 9 is balanced
    ) a + b (  ) a + b ( is NOT balanced
    ((x-y)/(9-z)  ((x-y)/(9-z) is NOT balanced
    noparens  noparens is balanced
    (((x-y)/(9-z)))  (((x-y)/(9-z))) is balanced

    The problem I'm having right now is that my program says example 2 is balanced even though the closed parens comes first. Here is the code that goes through the stack and checks if the parens are balanced or not.

    char stackChar = ' ';
    int count = 0;

    while(!stack1.empty() && count != -1) //until stack empty and while closed parens always follow open parens
    {
    stackChar = stack1.pop(); //get top char
    if(stackChar == '(') //if open parens, increment count
    count++;
    if(stackChar == ')') //if closed parens, decrement count
    count--;
    }

    If the closed parenthesis goes first, the program is still saying it's balanced. Why is this still happening? Thanks.
    Last edited by cjw92; 10-04-2011 at 10:29 PM.

Similar Threads

  1. Replies: 8
    Last Post: 12-14-2012, 01:34 PM
  2. Stack
    By kayln in forum Eclipse
    Replies: 0
    Last Post: 03-04-2011, 08:14 PM
  3. How big is the stack??
    By mgeno216 in forum New To Java
    Replies: 6
    Last Post: 03-04-2011, 08:04 AM
  4. Stack problem..pls help
    By Mika in forum New To Java
    Replies: 1
    Last Post: 02-16-2009, 08:10 AM
  5. Stack not popping
    By bugger in forum New To Java
    Replies: 2
    Last Post: 01-28-2008, 04:59 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •