I have this method which is supposed to cut a String when it finds a symbos of + or - (it is part of a derivative calculator, so the idea is to get a bunch of small strings separated by + or - and then derivate them one by one. That's why i have that search for opened and closed parenthesis) The problem is: When calling res = new String(); it will create a new String, but it will also set all the existing String objects in the array to null, which means the return of the method will always be an array with everything set to null (unless it does not find a + or - in the function). Is there a way around this?
public static String[] cutString(String func)
{
int number_strings_res = 0;
int number_parenthesis = 0;
String[] res = new String[1];
res[0] = new String(func);
for(int i = 0; i < func.length(); i++)
{
if(func.charAt(i) == '+' || func.charAt(i) == '-')
{
for(int j = 0; j < i; j++)
{
if(func.charAt(j) == '(')
number_parenthesis++;
if(func.charAt(j) == ')')
number_parenthesis--;
}
if(number_parenthesis == 0)
{
res[number_strings_res] = "";
for(int j = 0; j < i; j++)
{
res[number_strings_res] += func.charAt(j);
}
number_strings_res++;
res = new String[number_strings_res + 1];
res[number_strings_res] = new String(Character.toString(func.charAt(i)));
number_strings_res++;
res = new String[number_strings_res + 1];
res[number_strings_res] = new String();
}
}
}
return res;
}
res = new String[number_strings_res + 1]
allocates a new array and stores it to res
. So that's the source of the immediate problem. You should probably be using a List
, like ArrayList
, instead if you don't know how long the collection will be.