Click here to Skip to main content
15,894,720 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear web developers,

I have problem with the following JAVA code:
Java
class threeMatrix{

  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;

	  System.out.print(threeD[i][j][k]);

	}

	System.out.println();

      }

      System.out.println();

    }

  }

}


the 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 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 


But I want the output to be:
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 0 0 0 0	 0 2 4 6 8	 0 4 8 12 16
0 0 0 0 0	 0 3 6 9 12	 0 6 12 18 24
Posted
Updated 14-Dec-11 21:30pm
v2

It is very trivial, so I'll leave the code to you.

First, the first two for loops should be swapped:
Java
for (j=0;j<4;j++) {
    for (i=0;i<3;i++) {
        for (k=0;k<5;k++) {
           // code
        }
    }
}


Then it's just a case of getting your space, tab and linefeed at the right point.
It will always be easier if you learn to get the data in the right order first, then worry about what you are going to do with it.
 
Share this answer
 
v2
Do you mean this?
Java
public static void main(String[] args){
 
    int threeD[][][] = new int[3][4][5];
 
    int i,j,k;
 
    for(j=0;j<4;j++){
      for(i=0;i<3;i++){
	for(k=0;k<5;k++){
	  threeD[i][j][k] = i*j*k; 
          System.out.print(threeD[i][j][k]);
          System.out.print(" ");
	} 
        System.out.print("      ");
      }
      System.out.println("");
    } 
  }
}
 
Share this answer
 
Comments
TorstenH. 15-Dec-11 5:45am    
there you go - homework done.
Nagy Vilmos 15-Dec-11 9:52am    
Senor Carlo, you spoil him.
CPallini 15-Dec-11 13:44pm    
I don't think so, monsieur. :-)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900