如何解决java.lang.StringIndexOutOfBoundsException?

时间:2018-11-05 12:07:41

标签: android android-studio

在计算String时出现错误

java.lang.StringIndexOutOfBoundsException: length=4; regionStart=5; regionLength=2

我的实现如下。

private void initializeMyPLsAllotted() { 
    int theMonthWhenICame = Integer.parseInt(myDateHired.substring(5, 7)); //This line is showing the error 
    int theYearWhenICame = Integer.parseInt(myDateHired.substring(0,4)); 
    int theCurrentMonth = Integer.parseInt(todaysDate.substring(5, 7));
    int theCurrentYear = Integer.parseInt(todaysDate.substring(0, 4)); 
    int myTotalMonths = (theCurrentYear - theYearWhenICame)*12 + theCurrentMonth - theMonthWhenICame; 

    if (myTotalMonths > 6) {
        numberOfPLsAllotted = 2;
    } else {
        numberOfPLsAllotted = 0;
    }

    myPLs = numberOfPLsAllotted;
}

3 个答案:

答案 0 :(得分:1)

  

java.lang.StringIndexOutOfBoundsException:length = 4; regionStart = 5; regionLength = 2

它清楚地表明您的字符串的长度为4,并且您正尝试从索引5中获取子字符串。请确保您的字符串有效

您可以检查类似内容以避免崩溃您的应用

private void initializeMyPLsAllotted() { 
    if(myDateHired.length() > 7 && todaysDate.length() > 7){
        int theMonthWhenICame = Integer.parseInt(myDateHired.substring(5, 7));
        int theYearWhenICame = Integer.parseInt(myDateHired.substring(0,4)); 
        int theCurrentMonth = Integer.parseInt(todaysDate.substring(5, 7));
        int theCurrentYear = Integer.parseInt(todaysDate.substring(0, 4)); 
        int myTotalMonths = (theCurrentYear - theYearWhenICame)*12 + theCurrentMonth - theMonthWhenICame; 
        if(myTotalMonths>6) {
            numberOfPLsAllotted = 2;
        } else {
            numberOfPLsAllotted = 0;
        }
        myPLs = numberOfPLsAllotted;
    } else {
        // print some error message
    }
}

答案 1 :(得分:0)

StringIndexOutOfBoundsException表示您要尝试substring的部分不在字符串长度之内。

示例

String test = "123";
String testSubstringOne = test.substring(0, 1);
//testSubstringOne -> "1"

String testSubstringTwo = test.substring(0, 5);
//testSubstringTwo -> java.lang.StringIndexOutOfBoundsException

确保您的myDateHired具有您期望的值。

教练的提示

您说这些值来自服务器...也许您应该考虑以更友好的格式(例如json)返回数据。

答案 2 :(得分:0)

正如doc所说,IndexOutOfBoundsException将在以下情况下抛出:

  

如果beginIndex为负,或者endIndex大于长度   此String对象的值,或者beginIndex大于endIndex

因此请在使用前检查myDateHired