java – Printing out a 2D array in matrix format

java – Printing out a 2D array in matrix format

final int[][] matrix = {
  { 1, 2, 3 },
  { 4, 5, 6 },
  { 7, 8, 9 }
};

for (int i = 0; i < matrix.length; i++) {
    for (int j = 0; j < matrix[i].length; j++) {
        System.out.print(matrix[i][j] +  );
    }
    System.out.println();
}

Produces:

1 2 3
4 5 6
7 8 9

To properly format numbers in columns, its best to use printf. Depending on how big are the max or min numbers, you might want to adjust the pattern %4d. For instance to allow any integer between Integer.MIN_VALUE and Integer.MAX_VALUE, use %12d.

public void printMatrix(int[][] matrix) {
    for (int row = 0; row < matrix.length; row++) {
        for (int col = 0; col < matrix[row].length; col++) {
            System.out.printf(%4d, matrix[row][col]);
        }
        System.out.println();
    }
}

Example output:

 36 913 888 908
732 626  61 237
  5   8  50 265
192 232 129 307

java – Printing out a 2D array in matrix format

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  |

Leave a Reply

Your email address will not be published. Required fields are marked *