Search code examples
javaarraysmacosjava-3declipse-luna

3D Array with Java (testing example from "Java: The Complete Reference, 9th edition)


I was trying to reproduce a code from the book I am reading and can't get to make it work. Here is the code:

public class ThreeDArray {

public static void main(String[] args) {
    int threeD [][][] = new int [3][4][5];
    int i, j, k;
    for (i = 0; i < 3; i++) {
        for (j = 0; j < 4; j++) {
            for (k = 0; k < 5; k++) {
                threeD [i][j][k] = i*j*k;
            }
        }
        for (i = 0; i < 3; i++) {
            for (j = 0; j < 4; j++) {
                for (k = 0; k < 5; k++) {
                    System.out.print(threeD[i][j][k]+"  ");
                }
                System.out.println("");
            }
            System.out.println("");
        }
    }
}
}

I am getting this output:

0  0  0  0  0  
0  0  0  0  0  
0  0  0  0  0  
0  0  0  0  0  

0  0  0  0  0  
0  0  0  0  0  
0  0  0  0  0  
0  0  0  0  0  

0  0  0  0  0  
0  0  0  0  0  
0  0  0  0  0  
0  0  0  0  0  

I am getting all zeros here and I can't find the mistake here. Please advise what is wrong here.


Solution

  • Wrong bracket placement: your second for loop should be outside the first:

    int i, j, k;
    for (i = 0; i < 3; i++) {
        for (j = 0; j < 4; j++) {
            for (k = 0; k < 5; k++) {
                System.out.printf("%d %d %d %d %n", i, j, k, i * j * k);
                threeD [i][j][k] = i*j*k;
            }
        }
    } // move to here ...
    for (i = 0; i < 3; i++) {
        for (j = 0; j < 4; j++) {
            for (k = 0; k < 5; k++) {
                System.out.print(threeD[i][j][k]+"  ");
            }
            System.out.println("");
        }
        System.out.println("");
    }
    // ... from here
    

    With the way you had it you were incrementing i with your print loop, which meant your first loop of i exited on the second iteration. Now it prints:

    0  0  0  0  0  
    0  0  0  0  0  
    0  0  0  0  0  
    0  0  0  0  0  
    
    0  0  0  0  0  
    0  1  2  3  4  
    0  2  4  6  8  
    0  3  6  9  12  
    
    0  0  0  0  0  
    0  2  4  6  8  
    0  4  8  12  16  
    0  6  12  18  24