0

the mission is to convert a 2-dimensional array into a simple array and I try to copy the element of original array to the new array via for loop,for example

public static void main(String[] args) {
    int[][] a = new int[5][8];
    //initialize the 2-dimensional array with random number range(1~100)
    assignNestedArray(a);
    printNestedArray(a);
    int[] arr=new int[a.length*a[0].length];
    for(int i=0,k=0;i<a.length;++i,k+=a[i].length){
        System.arraycopy(a[i], 0, arr, k, a[i].length);         
    }
    System.out.println(Arrays.toString(arr));
}

public static void printNestedArray(int[][] a){
    for (int[] sub_arr : a) {
        for (int v : sub_arr)
            System.out.print(v+" ");
        System.out.println();
    }
}

public static void assignNestedArray(int[][] a){
    for (int i = 0; i < a.length; ++i)
        for (int j = 0; j < a[i].length; ++j)
            a[i][j] = (int) (Math.random() * 100);
}

which shows an Array index out of bounds exception exception

on the other hand, if I modify the array copy code like this:

for(int i=0,k=0;i<a.length;++i){
        System.arraycopy(a[i], 0, arr, k, a[i].length);
        k+=a[i].length;
    }

It works well, I wonder what is the difference between those two codes and how to write a for loop with 2 elements update each time. Any advice is appreciate, thank you.

LancelotHolmes
  • 659
  • 1
  • 10
  • 31
  • 2
    Read the error. You're attempting to access the row at index 5. You only have 5 rows though, so the indices only go to 4. – Carcigenicate Oct 09 '16 at 13:01
  • You're right, I just ignore the order of the execute process of for loop, it seems the increment of i was executed first and the increment of k just cause the exception. – LancelotHolmes Oct 09 '16 at 14:00

1 Answers1

1

Modify your loop. You are incrementing "i" first and than incrementing k so when i==4 it is again incrementing i which will be 5 and u will than access a[5] which will throw ArrayIndexOutOfBoundsException.

        for (int i = 0, k = 0; i < a.length; k += a[i].length,++i) {
            System.arraycopy(a[i], 0, arr, k, a[i].length);
        }
cody123
  • 2,040
  • 24
  • 29