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 ![>[*[]^[#$]%]%]$%
, 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)) && (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)) && (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.