Link to home
Start Free TrialLog in
Avatar of ScarletBlue
ScarletBlue

asked on

String Index out of range Error

Hi all

I have an error "String index out of range: -4". What does this error mean??
The error seems to be in this line of code "String group = gstr[i].substring(3,endposition);"
There are 21 groups that must be added to Vector vsap, but on the 20th time in the loop, it displays that error.

Here is my code
try{
  //get all grps in portal, return in string[]
gstr = igf.findGroups(igf.getSearchGroup(),0);

//sort the string
Arrays.sort(gstr, String.CASE_INSENSITIVE_ORDER);

if(gstr != null){
response.write("<script>alert(\"gstr:"+gstr.length+"\")</script>");
      
for(int i=0; i<gstr.length; i++){
response.write("<script>alert(\"i :"+i+"\")</script>");
endposition = gstr[i].indexOf(',');
String group = gstr[i].substring(3,endposition);

//if group starts with sapportal groups , add it to vector
if(group.startsWith("SAPPortal")){
response.write("<script>alert(\"grp:"+group+"\")</script>");
vsap.addElement(group);
}                              
}      
setVSap(vsap);
}//if gstr != null
else{
response.write("<script>alert(\"String [] grps is null\")</script>");
}      
                  
}//end try
catch(Exception e){
response.write("<script>alert(\"issues:"+e.getMessage()+"\")</script>");
}

Thanx
SB
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

You must check it's not out of range.

if (endposition < 0)
    return;
This may fix it:


if (endposition < 0)
    endposition = gstr[i].length();
       

>>if(gstr != null)

is redundant btw. You won't be able to sort a null array without an exception
Avatar of ScarletBlue
ScarletBlue

ASKER

I have my code in a function that returns a vector..
i have inserted the code you have suggested in the for loop after the if statement..
but it gives an error wanting it to return a vector....

what would i return?
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
thank u cehj, it works!
have a lovely day
SB
:-)