Reputation: 23
Here is the question :
Within the main method, create a 10x10x10 three dimensional array.
By making the use of nested for loops, store the value of the sum of each of its coordinate positions.
For example: position (3,4,8) = 3 + 4 + 5 = 15
Here is my code :
import java.util.Arrays;
public class threedim
{
public static void main(String args[])
{
int threeD[][][] = new int[10][10][10];
int i, j, k = 0;
for(i=0; i<10; i++)
for(j=0; j<10; j++) {
threeD[i][j] = k;
k++;
}
for(i=0; i<10; i++) {
for(j=0; j<10; j++)
System.out.print(threeD[i][j] + " ");
System.out.println();
}
System.out.println();
}
}
I receive an incompatible types: int cannot be converted to int[] error, can anyone help me ?
Thank you in advance :)
Upvotes: 0
Views: 127
Reputation: 1
Your problem is caused by the following line:
threeD[i][j] = k;
threeD[i][j] refers to the third dimension of your array. The third dimension of you array is a simple array.
So, to set/add k to this array, you should specify concrete index.
threeD[i][j][z] = k;
where z is another index.
Btw, in this particular example, you can use your k as "z":
threeD[i][j][k] = k;
Upvotes: 0
Reputation: 571
Since you have a three dimensional array, you need three nested loops:
int h, i, j, k = 0;
for (h=0; h<10; h++)
for(i=0; i<10; i++)
for(j=0; j<10; j++) {
threeD[h][i][j] = k; // Is that really, what you want to do?
// threeD[h][i][j] = h + i + j; seems to be the right thing to do according to your explanation
k++;
}
for (h=0; h<10; h++)
for(i=0; i<10; i++) {
for(j=0; j<10; j++)
System.out.print(threeD[h][i][j] + " ");
System.out.println();
}
Upvotes: 2