Gain
Gain

Reputation: 3863

i have a problem with exception "java.lang.ArrayIndexOutOfBoundsException"

i have a problem with exception "java.lang.ArrayIndexOutOfBoundsException" i wrote a program which have src array of 48 length then processes it to take each 6 indexes to another array using method arrayCopy and print each dst array for me it works fine it prints each 6 indexes from the initial array but at the end i get an exception help please . the algorithm is just a test because i want to use the arrayCopy in another algorithm so i don't need suggestion to change the algorithm . i hope it is clear fair enough

  public static void main(String [] arg) 
        {   
            int[] src = new int[48];
            for(int j=0;j<src.length;j++)
            {
                src[j]=j+1;
                System.out.print(src[j]+" ");
            }   
            System.out.println();
            int[] dst = new int[6]; 
            int from=0;
            for(int i=0;i<src.length;i++)
            {
                System.arraycopy(src, from, dst, 0, 6); // Copies 6 indexes from src starting at from into dst
                from=from+6;
                print(dst); 
                System.out.println();
            }



            } 

        public static void print(int [] dst)
        {
            for(int i=0;i<dst.length;i++)
                System.out.print(dst[i]+" ");   
        }

Upvotes: 0

Views: 584

Answers (2)

vicatcu
vicatcu

Reputation: 5837

The way you've written it, on the last iteration of your loop from + 5 = 53 which is greater than 47 (therefore out of bounds of source).

Upvotes: 0

Andreas Dolk
Andreas Dolk

Reputation: 114787

Try this:

for(int i=0;i<src.length;i+=6)  // increment i by value 6

Or use from in the for expression:

for(int from=0; from<src.length; from+=6) {
    System.arraycopy(src, from, dst, 0, 6); 
    print(dst); 
    System.out.println();
}

Upvotes: 3

Related Questions