How can I print out a simple int [][] in the matrix box format like the format in which we handwrite matrices in. A simple run of loops doesn\'t apparently work. If it helps
public static void printMatrix(double[][] matrix) {
for (double[] row : matrix) {
for (double element : row) {
System.out.printf("%5.1f", element);
}
System.out.println();
}
}
printMatrix(new double[][]{2,0,0},{0,2,0},{0,0,3}});
2.0 0.0 0.0
0.0 2.0 0.0
0.0 0.0 3.0
public class Matrix
{
public static void main(String[] args)
{
double Matrix [] []={
{0*1,0*2,0*3,0*4),
{0*1,1*1,2*1,3*1),
{0*2,1*2,2*2,3*2),
{0*3,1*3,2*3,3*3)
};
int i,j;
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
System.out.print(Matrix [i] [j] + " ");
System.out.println();
}
}
}
int[][] matrix = {
{1,2,3},
{4,5,6},
{7,8,9},
{10,11,12}
};
printMatrix(matrix);
public void printMatrix(int[][] m){
try{
int rows = m.length;
int columns = m[0].length;
String str = "|\t";
for(int i=0;i<rows;i++){
for(int j=0;j<columns;j++){
str += m[i][j] + "\t";
}
System.out.println(str + "|");
str = "|\t";
}
}catch(Exception e){System.out.println("Matrix is empty!!");}
}
Output:
| 1 2 3 |
| 4 5 6 |
| 7 8 9 |
| 10 11 12 |