2013-11-26 50 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元素在數組中。)