Adam Duffy
Posts: 168
Nickname: adamduffy
Registered: Feb, 2003
|
|
Re: balanced parenthesis function
|
Posted: Apr 23, 2003 2:52 AM
|
|
Hi Jake,
I ran it with the example shown in the comments, i.e. s)ss()a(dcf)a) and it threw an exception at the
if(parserStack.peek()=="(")
line of code. The peek method of java.util.Stack will throw EmptyStackException if the Stack is empty. This will occur at the first right parenthesis - the second character in the string mentioned above.
Suggest you modify the line to read
if(!parserStack.isEmpty() && parserStack.peek()=="(")
which will make sure the stack is not empty before you peek into it.
Furthermore, you might consider returning false on the else condition of this if statement, i.e.
if(str.charAt(i)==RIGHT_PAREN)
{
if(!parserStack.isEmpty() &&
parserStack.peek()=="(")
{
parserStack.pop();
}
else
{
// at this point, we have a right parenthesis
// without a left parenthesis coming before it
return false;
}
}
I do not see the need for the if statement outside the for loop, i.e.
if(str.charAt(0)!=RIGHT_PAREN)
You should be able to remove this without affecting your code.
All the best, Adam
|
|