Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 19 of 19

Thread: balancedBracketsByCounting (String s) that checks brackets are matched in the String.

  1. #1
    Junior Member
    Join Date
    Feb 2011
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default balancedBracketsByCounting (String s) that checks brackets are matched in the String.

    Hi, I need to write an algorithm balancedBracketsByCounting (String s), as follows, that takes a string as an input and checks whether the brackets "[" and "]" in the string are matched correctly.
    For example, balancedBracketsByCounting("[x][[xy]]") would return true but balancedBracketsByCounting("[[x[y]]") would return false.

    Do I need to use stack or queue?

    Please assist!
    Thanks.


  2. #2
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: balancedBracketsByCounting (String s) that checks brackets are matched in the Str

    The easiest way to do this is with a stack. Every time you see an opening brace/parenthesis/etc. push it onto the stack. Whenever you see a closing brace/parenthesis/etc. see if the item at the top matches that one, and if it does pop it off. Otherwise the brackets don't match. If you reach the end of the string and the stack isn't empty then that means you have an unbalanced number of braces/parenthesis/etc.

  3. #3
    Junior Member
    Join Date
    Feb 2011
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: balancedBracketsByCounting (String s) that checks brackets are matched in the Str

    helloworld922, Thanks for advice.

    Does this works?

    import java.util.*; 
     
    public class balancedBraces
    {
        public boolean  balancedBracesMethod (String s)
        {
            int myLength = s.length();
            Stack st = new Stack();
            char d;
     
            for (int i=0;i<s.length();i++)
            {
                char c = s.charAt(i);
                if (c == '(')
                {
                    st.push(new Character(c));
                }
                else if (c == '[') 
                {
                    st.push(new Character(c));
                }
                else if (c == ')')
                {
                    if (st.empty() == true)
                    {
                        return false;
                    }
                    else if (st.empty() == false)
                    {
                        d = (Character) st.pop();
                        if (d != '(')
                        {
                            return false;
                        }
                    }
                } 
                else if (c == ']')
                {
                    if (st.empty() == true)
                    {
                        return false;
                    }
                    else if (st.empty() == false)
                    {
                        d = (Character) st.pop();
                        if (d != '[')
                        {
                            return false;
                        }
                    }
                }
            }
     
            return true;
        }
    }
    Last edited by KevinWorkman; February 23rd, 2011 at 08:28 AM. Reason: added highlight tags

  4. #4
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: balancedBracketsByCounting (String s) that checks brackets are matched in the Str

    Quote Originally Posted by neonz View Post
    Does this works?
    You tell us. Did it work?

    When posting code, make sure you use the code or highlight tags. I've edited your post to include them this time.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  5. #5
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: balancedBracketsByCounting (String s) that checks brackets are matched in the Str

    It seems we're wasting our time by helping here, since this has been crossposted:

    This thread has been cross posted here:

    http://www.java-forums.org/new-java/39393-java-method-check-brackets-string-matched.html

    Although cross posting is allowed, for everyone's benefit, please read:

    Java Programming Forums Cross Posting Rules

    The Problems With Cross Posting

    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  6. #6
    Junior Member
    Join Date
    Feb 2011
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: balancedBracketsByCounting (String s) that checks brackets are matched in the Str

    Sorry, was trying to get fast response and resolve the problem.

    Another testing done. This time round is smooth testing. All the way test by entering new figure instead of hard-coding.

     
        public static void main (String args [])
        {
            boolean test = true;
            while(test)
            {
                BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 
                System.out.println("Enter test data: ");
                try
                {
                    String input = reader.readLine();      
                    boolean result = balancedBracesMethod (input);
                    System.out.println(result);
                }
                catch (IOException e)
                {
                    System.out.println("An unexpected error occured."); 
                }
            }
        }
    Hope I can get feed back on improving the program code, and make improvement.

  7. #7
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: balancedBracketsByCounting (String s) that checks brackets are matched in the Str

    Quote Originally Posted by neonz View Post
    Sorry, was trying to get fast response and resolve the problem.
    Hope I can get feed back on improving the program code, and make improvement.
    I get that. Other members may feel inclined to continue to help you despite the crossposting, but I for one will be spending my time elsewhere. To understand why, please read this: http://www.javaprogrammingforums.com...s-posting.html
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  8. #8
    Junior Member
    Join Date
    Feb 2011
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: balancedBracketsByCounting (String s) that checks brackets are matched in the Str

    Quote Originally Posted by KevinWorkman View Post
    I get that. Other members may feel inclined to continue to help you despite the crossposting, but I for one will be spending my time elsewhere. To understand why, please read this: http://www.javaprogrammingforums.com...s-posting.html
    Got it sorry!

    Hmm, I am pretty new to how this works?
    Are both the forum linked?
    Meaning to say that both forum registered account users are able to help you?

    Hmm, also does it mean that posting on the forum you are definitely expected to receive free help? Because I am afraid to limit myself and wait for help on one forum, and no one appear to give you help.

    Thanks for letting me know.

    If I limit myself to posting in one forum, and indicate in another forum as cross-posting, will that be alright?

  9. #9
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: balancedBracketsByCounting (String s) that checks brackets are matched in the Str

    Quote Originally Posted by neonz View Post
    Got it sorry!
    It's fine. It's not like you broke the law or anything. It's just that there are hundreds of other posts on this forum, and they presumably did not receive help elsewhere already, so I'm going to spend my time on them instead. It's nothing personal.

    Quote Originally Posted by neonz View Post
    Are both the forum linked?
    No. I just happened to be using both.

    Quote Originally Posted by neonz View Post
    Hmm, also does it mean that posting on the forum you are definitely expected to receive free help? Because I am afraid to limit myself and wait for help on one forum, and no one appear to give you help.
    If you ask a question the smart way (see my signature), you'll almost definitely receive help. But there are no guarantees, and no time frames, so your mileage may vary. However, I will say that doing things like crossposting will actually decrease your chances of getting help in the future. It's your call.

    Quote Originally Posted by neonz View Post
    If I limit myself to posting in one forum, and indicate in another forum as cross-posting, will that be alright?
    If you post a thread in multiple forums, it's good etiquette to at least include a link to the other threads in each post. That way people will know what help you've already received and won't have to waste their time repeating what you've already been told.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  10. #10
    Junior Member
    Join Date
    Feb 2011
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: balancedBracketsByCounting (String s) that checks brackets are matched in the Str

    Latest program:

    import java.util.*; 
    import java.io.*; 
     
    public class balancedBraces
    {
        public static boolean  balancedBracesMethod (String s)
        {
            int myLength = s.length();
            Stack st = new Stack();
            char d;
     
            for (int i=0;i<s.length();i++)
            {
                char c = s.charAt(i);
     
                if (c == '(')
                {
                    st.push(new Character(c));
                }
                else if (c == '[') 
                {
                    st.push(new Character(c));
                }
                else if (c == '{')
                {
                    st.push(new Character(c));
                }
     
                else if (c == ')')
                {
                    if (st.empty())
                    {
                        return false;
                    }
                    else
                    {
                        d = (Character) st.pop();
                        if (d != '(')
                        {
                            return false;
                        }
                    }
                } 
                else if (c == ']')
                {
                    if (st.empty())
                    {
                        return false;
                    }
                    else
                    {
                        d = (Character) st.pop();
                        if (d != '[')
                        {
                            return false;
                        }
                    }
                }
                else if (c == '}')
                {
                    if (st.empty())
                    {
                        return false;
                    }
                    else
                    {
                        d = (Character) st.pop();
                        if (d != '{')
                        {
                            return false;
                        }
                    }
                }
            }
     
            if (st.empty()) return true;
            else return false;
        }
     
        public static void main (String args [])
        {
            boolean test = true;
            while(test)
            {
                BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 
                System.out.println("Enter test data: ");
                try
                {
                    String input = reader.readLine();      
                    boolean result = balancedBracesMethod (input);
                    System.out.println(result);
                }
                catch (IOException e)
                {
                    System.out.println("An unexpected error occured."); 
                }
            }
        }
    }

    Please help to comment and check if there any problem.

    Cross-posted: Java method that check brackets in String are matched? - Java Forums

  11. #11
    Junior Member
    Join Date
    Feb 2011
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: balancedBracketsByCounting (String s) that checks brackets are matched in the Str

    Hope someone will take a look and help comment to see if everything work fine.
    Thanks, been a few days already and no one commented or reply.

    Thanks for all comment and reply.

  12. #12
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: balancedBracketsByCounting (String s) that checks brackets are matched in the Str

    Like I said, people don't love wasting their time on crossposters. I see you're still posting to the other forum, and I see that you haven't really responded to any of the suggestions you received in either forum. All of those things are very good ways to make sure people don't want to reply.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  13. #13
    Junior Member
    Join Date
    Feb 2011
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: balancedBracketsByCounting (String s) that checks brackets are matched in the Str

    Quote Originally Posted by KevinWorkman View Post
    Like I said, people don't love wasting their time on crossposters. I see you're still posting to the other forum, and I see that you haven't really responded to any of the suggestions you received in either forum. All of those things are very good ways to make sure people don't want to reply.
    I have mention it is a cross-posted thread.

    Before requesting for help, I waited for a few day before posting again.

    What are the suggestion I receive with regard to the program code that I haven't change or edited?

  14. #14
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: balancedBracketsByCounting (String s) that checks brackets are matched in the Str

    You received several suggestions on the other forum, and in fact you posted some code that you said works. What else do you want us to do? Asking us "is this right?" is pretty much useless- why don't you run it and tell us? What happens when you compile and run it? What happens when you test it? What else are you expecting us to say?
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  15. #15
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: balancedBracketsByCounting (String s) that checks brackets are matched in the Str

    From a quick scan-through it looks like it works. Have you tested it thoroughly? Designing a good test structure is as important if not more important than the actual program itself. Try running it on fragments you know will work and ones you know won't work. If you've done that, than it's probably a fairly safe bet that the code works as intended.

    The last thing I can think of is to comment your code, as well as pick logical names for your variables. Variable names such as c and d can be difficult to decipher what they're being used for.

  16. #16
    Junior Member
    Join Date
    Feb 2011
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: balancedBracketsByCounting (String s) that checks brackets are matched in the Str

    Quote Originally Posted by helloworld922 View Post
    From a quick scan-through it looks like it works. Have you tested it thoroughly? Designing a good test structure is as important if not more important than the actual program itself. Try running it on fragments you know will work and ones you know won't work. If you've done that, than it's probably a fairly safe bet that the code works as intended.

    The last thing I can think of is to comment your code, as well as pick logical names for your variables. Variable names such as c and d can be difficult to decipher what they're being used for.
    Thank you very much.
    Very helpful comment. Will test it part by part and will change the variable names.

    By the way, I am also requires to write the algorithm that outline the codes. Do you all know where to find the proper syntax in writing the algorithm?

    I know a bit about how to write the algorithm, not sure if I am right:

    1. No ' ; ' to be uses as it is use in different programing language and have different meaning.
    2. They look very similar to java coding.

    Are there many ways which you can write an algorithm?

  17. #17
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: balancedBracketsByCounting (String s) that checks brackets are matched in the Str

    Quote Originally Posted by neonz View Post
    Are there many ways which you can write an algorithm?
    There is no one way to write an algorithm. You could just spell it out as a series of steps, or you could use pseudo-code, or you could use flowcharts. That's up to you (or your instructor).
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  18. #18
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: balancedBracketsByCounting (String s) that checks brackets are matched in the Str

    One way I find very effective for writing algorithms is to use a state-machine diagram. It's basically a flow-chart, and provides the states (i.e. what to do) as circles, then arrows of conditions/flow control to connect the different states. Using a description like the one I provided you is also a good choice. It just needs to be something that can convey the idea of what your code is suppose to do without being bogged down too deeply into the syntax/specifics of the implementation.

  19. #19
    Junior Member
    Join Date
    Feb 2011
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: balancedBracketsByCounting (String s) that checks brackets are matched in the Str

    To: KevinWorkman and helloworld922

    Thanks for the advice.

    My problem is resolved.

Similar Threads

  1. [SOLVED] String Matcher finding only char not a whole string
    By Kakashi in forum What's Wrong With My Code?
    Replies: 11
    Last Post: February 18th, 2011, 09:58 AM
  2. Replies: 2
    Last Post: December 22nd, 2010, 09:21 AM
  3. How can I convert a String to Set<String>? Is it possible?
    By noFear in forum Java Theory & Questions
    Replies: 2
    Last Post: August 25th, 2010, 09:03 AM
  4. [SOLVED] why casting int to String is not possible through brackets method
    By voltaire in forum Java Theory & Questions
    Replies: 2
    Last Post: May 2nd, 2010, 04:00 PM
  5. Replies: 2
    Last Post: November 3rd, 2009, 06:28 AM