Printing out a 2D array in matrix format

198,874

Solution 1

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

Solution 2

To properly format numbers in columns, it's 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

Solution 3

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  |

Solution 4

In Java 8 fashion:

import java.util.Arrays;

public class MatrixPrinter {
  public static void main(String[] args) {
    final int[][] matrix = new int[4][4];
    printMatrix(matrix);
  }

  public static void printMatrix(int[][] matrix) {
    Arrays.stream(matrix).forEach((row) -> {
      System.out.print("[");
      Arrays.stream(row).forEach((el) -> System.out.print(" " + el + " "));
      System.out.println("]");
    });
  }
}

This produces:

[ 0  0  0  0 ]
[ 0  0  0  0 ]
[ 0  0  0  0 ]
[ 0  0  0  0 ]

But since we are here why not make the row layout customisable?

All we need is to pass a lamba to the matrixPrinter method:

import java.util.Arrays;
import java.util.function.Consumer;

public class MatrixPrinter {
  public static void main(String[] args) {
    final int[][] matrix = new int[3][3];

    Consumer<int[]> noDelimiter = (row) -> {
      Arrays.stream(row).forEach((el) -> System.out.print(" " + el + " "));
      System.out.println();
    };

    Consumer<int[]> pipeDelimiter = (row) -> {
      Arrays.stream(row).forEach((el) -> System.out.print("| " + el + " "));
      System.out.println("|");
    };

    Consumer<int[]> likeAList = (row) -> {
      System.out.print("[");
      Arrays.stream(row).forEach((el) -> System.out.print(" " + el + " "));
      System.out.println("]");
    };

    printMatrix(matrix, noDelimiter);
    System.out.println();
    printMatrix(matrix, pipeDelimiter);
    System.out.println();
    printMatrix(matrix, likeAList);
  }

  public static void printMatrix(int[][] matrix, Consumer<int[]> rowPrinter) {
    Arrays.stream(matrix).forEach((row) -> rowPrinter.accept(row));
  }
}

This is the result:

 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 ]

Solution 5

int[][] matrix = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
};
//use foreach loop as below to avoid IndexOutOfBoundException
//need to check matrix != null if implements as a method
//for each row in the matrix
for (int[] row : matrix) {
    //for each number in the row
    for (int j : row) {
        System.out.print(j + " ");
    }
    System.out.println("");
}
Share:
198,874
dawnoflife
Author by

dawnoflife

Updated on June 15, 2021

Comments

  • dawnoflife
    dawnoflife almost 3 years

    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 I'm trying to compile this code in a linux ssh terminal.

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