Results 1 to 1 of 1
- 10-04-2011, 11:16 PM #1Member
- Join Date
- Feb 2011
- Rep Power
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
if(stackChar == ')') //if closed parens, decrement 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 11:29 PM.
- By Neil_ in forum EclipseReplies: 8Last Post: 12-14-2012, 02:34 PM
- By kayln in forum EclipseReplies: 0Last Post: 03-04-2011, 09:14 PM
- By mgeno216 in forum New To JavaReplies: 6Last Post: 03-04-2011, 09:04 AM
- By Mika in forum New To JavaReplies: 1Last Post: 02-16-2009, 09:10 AM
- By bugger in forum New To JavaReplies: 2Last Post: 01-28-2008, 05:59 PM