The Artima Developer Community
Sponsored Link

Java Answers Forum
balanced parenthesis function

1 reply on 1 page. Most recent reply: Apr 23, 2003 2:52 AM by Adam Duffy

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
jake

Posts: 83
Nickname: onorok
Registered: May, 2002

balanced parenthesis function Posted: Apr 22, 2003 10:29 PM
Reply to this message Reply
Advertisement
this is supposed to return true if there is a balanced amount of parenthesis like a valid mathmatical expression, I am using a stack.
see if you can find any problems cause it doesn't work!

public boolean hasBalParens(String s)           
	{						// this should return false:  "s)ss()a(dcf)a)"
		final char LEFT_PAREN='(';
		final char RIGHT_PAREN=')';
		StringBuffer str = new StringBuffer(s);
		
		if(str.charAt(0)!=RIGHT_PAREN)
		{	
			for(int i=0; i<str.length(); ++i)
			{
				if(str.charAt(i)==LEFT_PAREN)
				{
					parserStack.push("(");
				}
			
				if(str.charAt(i)==RIGHT_PAREN)
				{
					if(parserStack.peek()=="(")
						parserStack.pop();
					
				}
			}
		}
 
		if(parserStack.isEmpty() && str.charAt(0)!=RIGHT_PAREN)
		{
			return true;
		}
		else
			return false;
			
	}


Adam Duffy

Posts: 168
Nickname: adamduffy
Registered: Feb, 2003

Re: balanced parenthesis function Posted: Apr 23, 2003 2:52 AM
Reply to this message Reply
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

Flat View: This topic has 1 reply on 1 page
Topic: consruct a timetable Previous Topic   Next Topic Topic: Working with text files

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use