2013-11-26 33 views
0
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。任何人都可以告诉我如何纠正这个异常?ArrayIndexOutOfBoundsException即将到来

+0

请问一个问题,当其可读性格式化你的代码,并告诉我们'result'的值。据推测它不包含空间。 –

+0

使用return Float.valueOf(retArray [0]); –

+0

我会假设'result'可能不包含任何空格,这意味着split将创建一个大小为1的数组(索引0)。 – Dragondraikk

回答

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

将假定retArray中至少有两个元素 - 这可能不是这种情况。
测试与retArray.length

+0

通过这样做,得到的异常喜欢在线程“主要” java.lang.NumberFormatException 例外:对于输入字符串:“-1报告” \t在java.lang.NumberFormatException.forInputString(来源不明) \t在java.lang.Integer中.parseInt(未知来源) \t在java.lang.Integer.valueOf(未知来源) \t在SMSServiceJava.CSoftHttpClientSMSService.getAccountMessageLimit(CSoftHttpClientSMSService.java:56) \t在SMSServiceJava.CSoftHttpClientSMSService.main(CSoftHttpClientSMSService.java:223) – Deepu

+0

很好的阅读错误 - 是'1&Report'整数 - 不!编程不像读心。你必须非常精确的是你想要你的程序做什么。 –

1

你可能及彼例外:

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

如果根据" "分裂,有时可能没有第二个元素。你需要检查:

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

请注意,我写条件只是为了演示问题。你可能想重新考虑你的逻辑。 还记得,在Java数组是从零开始,当你回到retArray[1],你实际上是在数组中返回第二个元素。

+0

通过这样做我得到NumberFormatException。 – Deepu

+0

@Deepu这是别的。确保'result'包含'float'值。 – Maroun

+0

是的,它的结果包含浮点值。 – Deepu

0

我想你一定先检查一下,如果阵列有任何数据或不

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

检查字符串结果,要么是空的,否则将有不具有空间数据定界符访问retArray之前还检查retArray的长度[1](由retArray [1]实际上你试图访问2元素在数组中。)