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]);
}
这里我收到 ArrayIndexOutBoundException。谁能告诉我如何纠正该异常?
最佳答案
您可能会在这里遇到异常:
String[] retArray = result.split(" ");
return Float.valueOf(retArray[1]);
如果按照" "
拆分,有时可能没有第二个元素。您需要检查:
String[] retArray = result.split(" ");
if(retArray.length >= 2) {
return Float.valueOf(retArray[1]);
}
请注意,我编写条件只是为了演示该问题。您可能需要重新考虑您的逻辑。
另请记住,当您返回 retArray[1]
时,Java 中的数组从零开始 ,您实际上返回了数组中的第二个元素。
关于java - ArrayIndexOutOfBoundsException 即将到来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20212360/