Page 1 of 2 12 LastLast
Results 1 to 20 of 22
  1. #1
    neonz is offline Member
    Join Date
    Feb 2011
    Posts
    10
    Rep Power
    0

    Default Java method that check brackets in String are matched?

    How to write balancedBracketsByCounting(String s), as follows, that takes a string as an input and checks whether the brackets "[", "]", "(", and ")" in the string are matched correctly?

    balancedBracketsByCounting("[x][[xy]]") would return True.
    balancedBracketsByCounting("[[x[y]]") would return False.

    Do we need to use Stack and Queue in our program?

    Please assist, thanks.

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default

    Count them?

  3. #3
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,525
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Tolls View Post
    Count them?
    Just counting them won't work if several types of brackets need to be checked, e.g. [({)}] is an incorrect pattern although the count of those brackets shows everything is fine; a simple stack is needed.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default

    Oh.
    Different ones in the same string.
    I was going by the OPs example...counting would work well enough there.
    :)

  5. #5
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,525
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Tolls View Post
    Oh.
    Different ones in the same string.
    I was going by the OPs example...counting would work well enough there.
    :)
    Yep, counting works fine for the special case of one type of parentheses but I, of course, generalized the whole thing to several types of brackets again ;-)

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  6. #6
    Ruuhkis is offline Member
    Join Date
    Feb 2011
    Posts
    19
    Rep Power
    0

    Default

    boolean brackets(String string, char start, char end){
    boolean check = false;
    boolean isBalance = true;
    for(char x: string.toCharArray()){
    if(x == start && !check){
    check = true;
    }else if(x == start && check){
    isBalance = false;
    }else if(x == end && !check){
    isBalance = false;
    }else if(x == end && check){
    check = false;
    }
    }
    return isBalance;
    }
    and for usage
    brackets("(thisisTest)", '(', ')');

  7. #7
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,525
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Ruuhkis View Post
    and for usage
    ... try this:

    Java Code:
    brackets("((thisisTest))", '(', ')');
    That algorithm doesn't work.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  8. #8
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default

    A spoonfeed that doesn't work?
    Who'd have thought it, eh?
    :)

  9. #9
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,525
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Tolls View Post
    A spoonfeed that doesn't work?
    Who'd have thought it, eh?
    :)
    Nothing surprises me anymore here ;-)

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  10. #10
    neonz is offline Member
    Join Date
    Feb 2011
    Posts
    10
    Rep Power
    0

    Default

    Quote Originally Posted by Tolls View Post
    Count them?
    Sorry to have confuse you with the method name, the main idea/ goal is to test if the brackets that is found in the String are matched correctly.

  11. #11
    neonz is offline Member
    Join Date
    Feb 2011
    Posts
    10
    Rep Power
    0

    Default

    Quote Originally Posted by JosAH View Post
    Just counting them won't work if several types of brackets need to be checked, e.g. [({)}] is an incorrect pattern although the count of those brackets shows everything is fine; a simple stack is needed.

    kind regards,

    Jos

    Thanks Josah for enlightenment ...

    Does this work?

    =========================================

    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 neonz; 02-23-2011 at 09:14 AM.

  12. #12
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default

    Use code tags for starters.

    Also wouldn't it be easier for you to actually run this with some test code than ask us to read through it and try and spot mistakes?

    I will say that:
    Java Code:
    if (st.empty() == true)
    {
    ...
    }
    else if (st.empty() == false)
    {
    ...
    }
    should be:
    Java Code:
    if (st.empty())
    {
    ...
    }
    else
    {
    ...
    }
    Comparing a boolean to true or false is is unecessary,

  13. #13
    neonz is offline Member
    Join Date
    Feb 2011
    Posts
    10
    Rep Power
    0

    Default

    Quote Originally Posted by Tolls View Post
    Use code tags for starters.

    Also wouldn't it be easier for you to actually run this with some test code than ask us to read through it and try and spot mistakes?

    I will say that:
    Java Code:
    if (st.empty() == true)
    {
    ...
    }
    else if (st.empty() == false)
    {
    ...
    }
    should be:
    Java Code:
    if (st.empty())
    {
    ...
    }
    else
    {
    ...
    }
    Comparing a boolean to true or false is is unecessary,
    True, point taken ... If (condition in loop is true), then the If loop will work.

  14. #14
    neonz is offline Member
    Join Date
    Feb 2011
    Posts
    10
    Rep Power
    0

    Default

    public static void main (String args [])
    {
    String s = "( [ ] )";
    boolean result = balancedBracesMethod (s);
    System.out.print(result);
    }

    Have done this test with String s used.
    Program seems to be working fine.

    )([] return false
    [()()] return true
    [)()(] return false
    ()][ return false

    Result return are expected.

  15. #15
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,963
    Rep Power
    8

    Default

    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  16. #16
    neonz is offline Member
    Join Date
    Feb 2011
    Posts
    10
    Rep Power
    0

    Default

    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 [])
    {
    while(true)
    {
    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.

  17. #17
    neonz is offline Member
    Join Date
    Feb 2011
    Posts
    10
    Rep Power
    0

    Default

    Latest program:

    [highlight=Java]
    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.");
    }
    }
    }
    }
    [/highlight]

    Please help to comment and check if there any problem.

    Cross-posted: balancedBracketsByCounting (String s) that checks brackets are matched in the String.

  18. #18
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,525
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by neonz View Post
    I can see that; the highlight tag is a valid tag in the other forum ;-)

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  19. #19
    neonz is offline Member
    Join Date
    Feb 2011
    Posts
    10
    Rep Power
    0

    Default

    Hi JosAH and KevinWorkman,

    Any problem with my above mini-java program?

    I have been fine-tuning it, to the last version alry.

    Any other way to code the java program such that it is shorter or more efficient?

    Please assist, thanks.

    So far no one really got back to me on the java program, if there is any error any where, please do tell me.

    Thank.

  20. #20
    neonz is offline Member
    Join Date
    Feb 2011
    Posts
    10
    Rep Power
    0

    Default

    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.

Page 1 of 2 12 LastLast

Similar Threads

  1. check string inside string
    By alacn in forum New To Java
    Replies: 8
    Last Post: 07-07-2010, 12:52 PM
  2. Replies: 1
    Last Post: 04-30-2010, 03:21 PM
  3. Check method
    By XMarkoX in forum New To Java
    Replies: 5
    Last Post: 11-24-2009, 12:54 PM
  4. flipping memory cards if they are not matched...
    By yanipao in forum New To Java
    Replies: 8
    Last Post: 10-18-2009, 02:25 AM
  5. check command method please
    By dirtycash in forum New To Java
    Replies: 1
    Last Post: 12-06-2007, 09:35 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
  •