-1
boolean Match(char c) {
    if (this.type == '[' && c == ']')
        return true;
    if (this.type == '{' && c == '}')
        return true;
    if (this.type == '(' && c == ')')
        return true;
    return false;
}




    Stack<Bracket> opening_brackets_stack = new Stack<Bracket>();
    for (int position = 0; position < text.length(); ++position) 
    {
        char next = text.charAt(position);

        if (next == '(' || next == '[' || next == '{') 
        {
            // Process opening bracket, write your code here
            Bracket temp = new Bracket(next,position);
            opening_brackets_stack.push(temp);
        }

        if (next == ')' || next == ']' || next == '}') 
        {
            // Process closing bracket, write your code here
            try{
                Bracket item = opening_brackets_stack.pop();
                if(!item.Match(next)) 
                {  //not match
                    System.out.println(position+1);  
                    return;
                }
            }   
            catch(EmptyStackException e){}
        }
    }
    // Printing answer, write your code here
    try{
        if(opening_brackets_stack.isEmpty()) 
        {
          System.out.println("Success");
        }
        else {
            Bracket item = opening_brackets_stack.pop();
            //print position of first unmatched opening bracket
            System.out.println(item.position+1);
        }
    }
    catch (EmptyStackException e){}

}

i am getting wrong answer in cases like "}","()}" in which bracket is at last position. i am supposed to get answer "1","3" respectively for above cases but i am getting "Success". In all other cases, it works perfectly fine. What should I do?

  • 2
    you should never have empty catch blocks. At least print the stacktrace if one of your EmptyStackException happens. How do you currently even know if your code isn't throwing just exceptions if you just ignore them. – OH GOD SPIDERS Apr 24 '20 at 12:24
  • *"What should I do?"* **Debug** your code. Don't ask us to do your debugging for you. [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173/5221149). – Andreas Apr 24 '20 at 12:24

1 Answers1

1

With a string like "}", your code tries to pop an opening brace from the stack. But the stack is empty so you get an EmptyStackException, and control is transferred to your exception handler. Which does nothing.

Rather than trying to catch an exception, check to see if the stack is empty. If it is, then you know that you have too many closing braces. Treat it the same way you'd treat a false return from item.Match.

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351