2017-02-23 90 views
-2
public static float getSelectedHeight() { 
    String selectedHeightValue = (String)heightSpin.getSelectedItem(); 
    if (heightSpin.getSelectedItemPosition() == 0) { 
    String feets = selectedHeightValue.substring(0,1); 
    String inches = selectedHeightValue.substring(2,4); 

    return (float) (Float.parseFloat(feets) * 0.3048) + (float) (Float.parseFloat(inches) * 0.0254); 

    } else { 
    return Float.parseFloat(selectedHeightValue); 
    } 
} 

錯誤字符串索引出界異常的,我不知道如何解決它。請幫我解決這個問題如何在我的情況下解決StringIndexOutOfBoundsException?

**java.lang.StringIndexOutOfBoundsException: length=2; regionStart=2; regionLength=2** 

回答

0

的問題可能是線,selectedHeightValue.substring(...)

要解決它,首先作爲一個大拇指拇指,在做任何與子字符串的操作之前,你應該檢查selectedHeightValue必須是有效的(所以不是NULL和不EMPTY)。

然後確保您的string size足以生成它的子字符串(以便在您嘗試訪問不存在的字符串中的位置時它不超過其大小)。

Exmple:字符串「ABC」的大小爲3.並且具有位置:0,1,2。如果你嘗試在位置3和上(4,5,6 ...)訪問字符串「ABC」,比我想要拋出一個錯誤,因爲你想訪問一些不存在的東西。

+0

你知道你的'經驗法則'在Java中錯了嗎?字符串比較必須用'equals'來完成。 – 0xDEADC0DE

+0

@ 0xDEADC0DE謝謝我寫作時很忙。我更新了答案。 :) –

相關問題