Reputation: 53
How do you format an 2 dimensional array so that prints out a sort of matrix "Style".
For example in this snippet of code array is getting two the product of two ,two dimensional int arrays.
Say a 2x2 matrix that is like this
59 96
78 51
In the command prompt when printed out it ends up being displayed like this
59 96 78 51
how do you make it be display in the matrix type format of row and columns.
2X2 is just an example in this program the 2d arrays have to be greater or equal to 50.
else
{
int[][] array;
//this will hold the multiplied thing
array=multiply(matrix,matrix2);
System.out.println("this is the result of the multiplication");
//print out the array
for(int i=0; i<row; i++)
{
for( int j=0; j< col2; j++)
{
System.out.print(array[i][j] + " \t");
}
}
Upvotes: 2
Views: 143
Reputation: 599
or making a method like this
public static void printMatrix(int[][] mat) {
System.out.println("Matrix["+mat.length+"]["+mat[0].length+"]");
int rows = mat.length;
int columns = mat[0].length;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.printf("%4d " , mat[i][j]);
}
System.out.println();
}
System.out.println();
}
and call it from your main program
printMatrix(array);
Upvotes: 0
Reputation: 383
Add one line to your code:
System.out.println("this is the result of the multiplication");
//print out the array
for(int i=0; i<row; i++)
{
for( int j=0; j< col2; j++)
{
System.out.print(array[i][j] + " \t");
}
System.out.println();
}
Upvotes: 0
Reputation: 1595
This should work, but such formating in pretty way is not so easy.
for(int i=0; i<row; i++) {
for( int j=0; j< col2; j++) {
System.out.print(array[i][j] + " \t");
}
System.out.println();
}
Upvotes: 2