简体   繁体   English

Android:数组索引超出范围错误

[英]Android: Array Index Out Of Bounds Error

I am trying to convert a string containing date to a char array and then extract the month and convert it. 我试图将包含日期的字符串转换为char数组,然后提取月份并将其转换。

I'm using API, the server provide date in the format: "2015-04-10", I'm trying to convert this into: "10 April, 2015." 我正在使用API​​,服务器以以下格式提供日期:“ 2015-04-10”,我正尝试将其转换为:“ 2015年4月10日”。

  1. Im storing the date received from server is in a string. 我存储从服务器收到的日期是一个字符串。
  2. I'm converting the entire string into a char array. 我将整个字符串转换为char数组。
  3. I'm running a loop through this array and separating it into three arrays: YEAR, MONTH, DAY. 我正在遍历此数组并将其分为三个数组:YEAR,MONTH,DAY。
  4. I'm separately converting these arrays to strings. 我将这些数组分别转换为字符串。
  5. Then I'm comparing the 'month' string to values and then assigning the month name to it, using if-else conditions. 然后,我将'month'字符串与值进行比较,然后使用if-else条件为其指定月份名称。
  6. Lastly, I'm adding the three strings as per the order I want. 最后,按照我想要的顺序添加三个字符串。

Android Studio says: java.lang.ArrayIndexOutOfBoundsException: length=2; index=5 Android Studio说: java.lang.ArrayIndexOutOfBoundsException: length=2; index=5 java.lang.ArrayIndexOutOfBoundsException: length=2; index=5

Here is my code: ('temp' is the string containing the date) 这是我的代码:(“ temp”是包含日期的字符串)

//TODO: Here lies the method which will apparently convert the movie string to human read-able format...... Use it with caution.
    char release[] = temp.toCharArray();
    Log.d("LOG", release.toString());

    char date[] = new char[2];
    char year[] = new char[4];
    char month[] = new char[2];

    for (int i = 0; i < 11; i++) {

        try {
            if (i > 4 && i < 7) {
                month[i] = release[i];
            }

            if (i < 4) {
                year[i] = release[i];    // ---> Android Studio says error on this line...
            }

            if (i > 7 && i < 10) {
                date[i] = release[i];
            }
        } catch (Error error) {
            error.printStackTrace();
        }
    }

    String monthString = month.toString();
    String dateString = date.toString();
    String yearString = year.toString();
    String finalReleaseDate;

    if (monthString.contentEquals("01")) {
        monthString = "January";
    } else if (monthString.contentEquals("02")) {
        monthString = "February";
    } else if (monthString.contentEquals("03")) {
        monthString = "March";
    } else if (monthString.contentEquals("04")) {
        monthString = "April";
    } else if (monthString.contentEquals("05")) {
        monthString = "May";
    } else if (monthString.contentEquals("06")) {
        monthString = "June";
    } else if (monthString.contentEquals("07")) {
        monthString = "July";
    } else if (monthString.contentEquals("08")) {
        monthString = "August";
    } else if (monthString.contentEquals("09")) {
        monthString = "September";
    } else if (monthString.contentEquals("10")) {
        monthString = "October";
    } else if (monthString.contentEquals("11")) {
        monthString = "November";
    } else if (monthString.contentEquals("12")) {
        monthString = "December";
    }

    finalReleaseDate = dateString + " " + monthString + ", " + yearString;
    movieModel.setReleaseDate(finalReleaseDate);

The message in logcat is: java.lang.ArrayIndexOutOfBoundsException: length=2; index=5 logcat中的消息是: java.lang.ArrayIndexOutOfBoundsException: length=2; index=5 java.lang.ArrayIndexOutOfBoundsException: length=2; index=5 (I have marked the line at which this error is shown..) java.lang.ArrayIndexOutOfBoundsException: length=2; index=5 (我已在显示此错误的行上进行了标记。)

Please help!! 请帮忙!!

You are iterating over i from 0 to 11 release array contains 10 digits only so you should iterate from 0 to 9 您要在0到11的i上进行迭代,所以发布数组仅包含10位数字,因此您应该在0到9之间进行迭代

Oh Wait that is not your problem, you main problem that year only contains 4 objects from 0 to 3 so you cannot get item i when i is greater that 3 哦,这不是您的问题,您的主要问题是那一年只包含4个对象(从0到3),所以当大于3时,您将无法获得项目i

Is that all I guess not... the log cat says the index=5 so the error occurred when i is 5, but the line you are saying is included when i is smaller than 4, So I guess you read the log cat wrong. 那是我猜不到的吗...日志猫说index=5所以当为5时发生了错误,但是当小于4时就包括了您要说的行,所以我想您看错了日志猫。

And Also it says the length is 2 so it crashed when reading either date array or month array but no way when it read the year array 而且它还说长度为2,所以在读取日期数组或月份数组时会崩溃,但在读取年份数组时却没办法

I brief as @Ken Wolf Wolf in the comment you can use SimpleDateFormat 我在评论中以@Ken Wolf Wolf的身份简要介绍了您可以使用SimpleDateFormat

SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-mm-dd", Locale.getDefault());
Date date = simpleDate.parse("");
simpleDate = new SimpleDateFormat("dd MMMM, yyyy.", Locale.getDefault());
String newFormatString = simpleDate.format(date);

First , you method is not the best way to convert number month to string month . 首先 ,方法不是将数字月份转换为字符串月份的最佳方法。 It should be easier and more stable to convert it by using Date and SimpleDateFormat method. 使用DateSimpleDateFormat方法进行转换应该更容易,更稳定。


Second , you have marked the wrong line for the crash. 其次 ,您为崩溃标记了错误的行。 This crash (java.lang.ArrayIndexOutOfBoundsException: ***length=2; index=5***) tells you that index is 5 and array length is 4 . 崩溃(java.lang.ArrayIndexOutOfBoundsException: ***length=2; index=5***)告诉您index为5数组长度为4

if (i < 4) {
   year[i] = release[i];  //index 5 cannot be called here and year lenght is 4
}
if (i > 4 && i < 7) {
   month[i] = release[i]; //index 5 is called here and month lenght is 2
}
if (i > 7 && i < 10) {
   date[i] = release[i];
}

Crash is happening because you are calling month[5] = release[5]; 发生崩溃是因为您正在调用month[5] = release[5]; and month length is only 2. 而月份长度仅为2。

To avoid this change your code to: 为了避免这种情况,请将您的代码更改为:

if (i<4) {
    //2015 index  0,1,2,3
    year[i] = release[i];
} else if (i>4 && i<7) {
    //04 index  5,6
    month[i-5] = release[i];
} else if (i>7 && i<10) {
    //10 index 8,9
    date[i-8] = release[i];
}

Third , if you want to get year, month, day in this way it is easier in this way. 第三 ,如果您希望以这种方式获取年,月,日,则这种方式会更容易。

String [] date_splited = server_string.split("-");
String year  = date_splited[0];
String month = date_splited[1];
String day   = date_splited[2];

Hope it helps you. 希望对您有帮助。

The problem is not occuring at the place that you say. 您说的地方不会发生此问题。 It probably occurs at the first or the thrid if statement. 它可能发生在第一个或第三个if语句中。 Because date[] and month[] are both only 2 in length, and you are trying to access that with index higher than 2. 因为date []和month []的长度都只有2,所以您尝试访问索引大于2的那个。

The proper way should be using SimpleDateFormat as Omar marked. 正确的方法应该使用Omar标记的SimpleDateFormat。 Once you have a Date (or a Calendar maybe depending the use you will give to the information) you can use the local settings to translate it. 一旦有了日期(或日历,可能取决于信息的用途),就可以使用本地设置来翻译它。

why you use char[] ? 为什么使用char []? you can use String[] directly. 您可以直接使用String []。 In string there is split method available. 在字符串中,有可用的拆分方法。 So using split method you can separate date month and year. 因此,使用拆分方法可以将日期月份和年份分开。 You can use below code: 您可以使用以下代码:

String date=  "2015-04-10";
String[] temp= date.split("-");

temp[0] is 2015, temp[1] is 04 and temp[1] is 10. temp [0]为2015,temp [1]为04,temp [1]为10。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM