Loop for finding proper grouping brackets I've got this piece of code that you pass a string of special characters to and an index which points to a location in this string. The code will take the index, analyze the string, and return a new index of location of the proper grouping bracket. I.e., if index = 5, and my string is ![&gt;[*[]^[#$]%]%]$%, I will be currently at ]. Then, I need to backtrace in the string to find its matching group bracket [. To do this, I've written the following method:

public static int jump(int current, String code){
    int count = 1;
    boolean flag = false;
    if('[' == code.charAt(current)){
      current++;
      while(flag == false){
        if('[' == code.charAt(current)) count++;
        else if(']' == code.charAt(current)) count--;
        if((']' == code.charAt(current)) &amp;&amp; (count ==0)){
          flag = true;
          break;
        }
        current++;
      } 
    }

    else{
      current--;
      while(flag == false){
        if(']' == code.charAt(current)) count++;
        else if('[' == code.charAt(current)) count--;
        if(('[' == code.charAt(current)) &amp;&amp; (count ==0)){
          flag = true;
          break;
        }
        current--;
      }
    }
    return current;
  }


But the more I look at this code the more I feel like "there's got to be a smarter way of doing it then a bunch of if-statements, a while loop, and a flag." But I'm not good enough at this point to figure out how to simplify what I've written (or the logic) into more readable, or smarter code. So I was hoping to find ways to improve this code since I find myself writing this kind of code from time to time and would like to improve the style if possible.
The most common approach to bracket matching is using a stack. 

Unmatched brackets you encounter are pushed onto the stack. When encountering a matching bracket pop the stack (and verify if it's the correct type of bracket, maybe not needed in your case). If the stack is empty after finding a match, the last match was the position you were looking for.

This approach, as you can see, also immediately allows for bracket matching validation, and can handle different types of brackets in the same String

To boot, the code is simpler.

Note

When looking for a stack implementation in Java, you may come across java.util.Stack; don't use that, use java.util.ArrayDeque instead, as the Stack javadoc itself suggests.