Deepu
Deepu

Reputation: 11

ArrayIndexOutOfBoundsException coming

public float getAccountBalance()    {       //log.debug("in getAccountBalance");
    PostMethod method = new PostMethod(smsServiceUrl);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
    method.setParameter("Username", username);
    method.setParameter("PIN", PIN);
    method.setParameter("AvailableCredit", "");
    String result = new String();
    try {
        result = doHttpServiceRequest(method);
    //  log.debug("result is: " + result);
    } catch (Exception e) {
    //  log.warn(e.toString());
    }

    String[] retArray = result.split(" ");
    return Float.valueOf(retArray[1]);

}

Here i am getting ArrayIndexOutBoundException. can any one tell me how to rectify that exception?

Upvotes: 0

Views: 124

Answers (4)

Prashant Thakkar
Prashant Thakkar

Reputation: 1403

Check String result, either it will be empty or it will have data which doesn't have space delimiter also check the length of the retArray before access retArray[1] (by retArray[1] actually you are trying to access 2 element in the array.)

Upvotes: 0

AGupta
AGupta

Reputation: 5734

I think you must check first, if array have any data or not

if(retArray.length>0)
{
  // do your thing
}
else
{
   // no element found
}

Upvotes: 0

Scary Wombat
Scary Wombat

Reputation: 44813

String[] retArray = result.split(" ");
return Float.valueOf(retArray[1]);

will assume that there is at least two elements in the retArray - this may not be the case.
Test with retArray.length

Upvotes: 0

Maroun
Maroun

Reputation: 95948

You're probably getting the exception here:

String[] retArray = result.split(" ");
return Float.valueOf(retArray[1]);

If you split according to " ", sometimes there might be no second element. You need to check that:

String[] retArray = result.split(" ");
if(retArray.length >= 2) {
   return Float.valueOf(retArray[1]);
}

Note that I write the condition only to demonstrate the issue. You might want to reconsider your logic. Also recall that arrays in Java are zero-based, when you return retArray[1], you're actually returning the second element in the array.

Upvotes: 1

Related Questions