-1

I wrote a method to insert a character in an string array periodically. I wrote it in android studio, and the application stops running. My input is an array of string: (The part of input is just for test, and I will make it dynamic)

    String[] myPoints= new String[4];
    myPoints[0]="22";
    myPoints[1]="45";
    myPoints[2]="34";
    myPoints[3]="60";

Now I need to insert ", " between each two records of array. So I wrote this:

public static String[] insertPeriodically(String[] points){


    int pointsSize = points.length;// length of points array
    int withCommosSize=pointsSize+(pointsSize/2)-1;//length of new array
    String[] withCommos= new String[withCommosSize];
    int insert=0;
    int k=0;
    for (int i=0; i<pointsSize; i=i++){
        withCommos[k]=points[i];
        insert=insert+1;
        if(insert==2){
            withCommos[k+1]=",";
            k++;
            insert=0;
        }else
        k++;
    }
    return withCommos;
}

The console shows this java error: java.lang.RuntimeException: Unable to start activity ComponentInfojava.lang.ArrayIndexOutOfBoundsException: length=5; index=5

Do you have any suggestion where is the problem?

roya zamiri
  • 157
  • 1
  • 2
  • 15

3 Answers3

1

There's a typo in your for loop (i=i++), and you should always increment k at least once. This works:

public static String[] insertPeriodically(String[] points){
    int pointsSize = points.length;// length of points array
    int withCommosSize=pointsSize+(pointsSize/2)-1;//length of new array
    String[] withCommos= new String[withCommosSize];
    int insert=0;
    int k=0;
    for (int i=0; i<pointsSize; i++){
        withCommos[k]=points[i];
        insert=insert+1;
        if(insert==2 && k<withCommosSize-1){
            withCommos[k+1]=",";
            k++;
            insert=0;
        }
        k++;
    }
    return withCommos;
}
JP Moresmau
  • 7,388
  • 17
  • 31
0

May be how about this

List<String> list = new ArrayList<String>();
for(int i=0;i<points.length;i++)
            {
                list.add(points[i]);
                if(i==(points.length-1)) break;
                list.add(",");
            }
Rookie007
  • 1,229
  • 2
  • 18
  • 50
0

Unable to start activity ComponentInfojava.lang.ArrayIndexOutOfBoundsException:

You are getting this exception because of i=i++. Check this link

This statement will not increase the value of i but you are increasing value of k every time(using if or else). Since i is not increasing your for loop will run in infinite-loop. And once value of k is greater than withCommosSize you will get ArrayIndexOutOfBoundsException.

Change i=i++ to i++ and It will work.

Community
  • 1
  • 1
NightWatcher
  • 148
  • 10