# 3D Array -- Adding Elements

• 11-18-2013, 12:16 AM
mynorka
I'm working on a project where I need to initialize a multidimensional array where each element in the array is the sum of the indices it took to get there.
So, array[5][7][9] will contain the contain the value 5 + 7 + 9 = 21. However, when I loop through the array to set a value to each index, I come up one index short on each dimension. For example, I only get to array[4][6][8].

Code:

```        public static void main(String[] args) throws IllegalAccessException,                                                                                         InstantiationException {                 Integer[][][] array = new Integer[5][7][9];                                 for(int i = 0; i < array.length; i++){                         for(int j = 0; j < array[0].length; j++){                                 for(int k = 0; k < array[0][0].length; k++){                                         array[i][j][k] = i + j + k;                                 }                         }                 }               System.out.println(array[5][7][9]);         }```
I end up getting an array out of bound exception when I try to print out the last element.
• 11-18-2013, 12:43 AM
Norm
Re: 3D Array -- Adding Elements
Quote:

getting an array out of bound exception
The range of valid index values ranges from 0 to the array length-1
• 11-18-2013, 06:31 AM
mynorka
Re: 3D Array -- Adding Elements
I understand that. I need to understand how I can get the values of each array index to be the sum of the subscripts. So, if I have a 3D array with dimensions 5x7x9, the element array[5][7][9] is 5+7+9 = 21. When I test it though, the maximum index I reach is array[4][6][8].
• 11-18-2013, 10:53 AM
JosAH
Re: 3D Array -- Adding Elements
If an array has n elements, the indexes of the elements are 0, 1, 2, ... ,n-1; so if an array has [5][7][9] elemtents, there doesn't exist an element arrays[5][7][9] ...

kind regards,

Jos
• 11-18-2013, 01:49 PM
Norm
Re: 3D Array -- Adding Elements
Quote:

I understand that.
Are you sure that you understand? Your reply said that you did not understand.