[java] printing out a 2-D array in Matrix format

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();
}

This question is related to java

The answer is


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

In java8 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 ]

    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("");
    }

public static void main(String[] args) 
        {
             int [] [] ar= 
                {
                        {12,33,23},
                        {34,56,75},
                        {14,76,89},
                        {45,87,20}

                };

I prefer using enhanced loop in Java

Since our ar is an array of array [2D]. So, when you iterate over it, you will first get an array, and then you can iterate over that array to get individual elements.

             for(int[] num: ar)
             {
                 for(int ele : num)
                 {
                 System.out.print(" " +ele);
                 }
                 System.out.println(" " );
             }

              }

Here's my efficient approach for displaying 2-D integer array using a StringBuilder array.

public static void printMatrix(int[][] arr) {
    if (null == arr || arr.length == 0) {
        // empty or null matrix
        return;
    }

    int idx = -1;
    StringBuilder[] sbArr = new StringBuilder[arr.length];

    for (int[] row : arr) {
        sbArr[++idx] = new StringBuilder("(\t");

        for (int elem : row) {
            sbArr[idx].append(elem + "\t");
        }

        sbArr[idx].append(")");
    }

    for (int i = 0; i < sbArr.length; i++) {
        System.out.println(sbArr[i]);
    }
    System.out.println("\nDONE\n");
}

enter image description here


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();
      }
   }
}

public static void printMatrix(double[][] matrix) {
    for (double[] row : matrix) {
        for (double element : row) {
            System.out.printf("%5.1f", element);
        }
        System.out.println();
    }
}

Function Call

printMatrix(new double[][]{2,0,0},{0,2,0},{0,0,3}});

Output:

  2.0  0.0  0.0
  0.0  2.0  0.0
  0.0  0.0  3.0

In console:

Console Output


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  |