0

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.

1
  • Okay, you've shown us what's not supposed to happen, but haven't told us what's supposed to happen instead. Commented Jan 20, 2015 at 20:47

1 Answer 1

1

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

2 Comments

Thanks Andy! I can't believe I missed that.
@fthnm2014. For what it's worth, I would avoid declaring int for a loop outside the for. Put your bracket in the wrong place again, but remove the int i, j, k declarations and declare your for loops as for (int ...). Your compiler would have probably thrown an error along the lines of Duplicate local variable i that you would have spotted it.

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.