0

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]+" ");   
        }
1
  • Can you indicate exactly which line the exception is thrown? Commented Dec 14, 2010 at 15:21

2 Answers 2

3

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();
}
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, this looks like the solution, I think.
thank you it works , like to your answer and (star * Infinity)
0

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.