27

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

11 Answers 11

48
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 
Sign up to request clarification or add additional context in comments.

Comments

27

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 

Comments

17
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 | 

Comments

5

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 ] 

Comments

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

Comments

2
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

Comments

1

Since Java 8:

int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; Arrays.stream(matrix).map(Arrays::toString).forEach(System.out::println); 

Output:

[1, 2, 3] [4, 5, 6] [7, 8, 9] 

Comments

0

Here's my efficient approach for displaying 2D 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"); } 

Output:

( 1 2 3 ) ( 4 5 6 ) ( 7 8 9 ) ( 10 11 12 ) DONE 

Comments

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

Output:

0.0 0.0 0.0 0.0 0.0 1.0 2.0 3.0 0.0 2.0 4.0 6.0 0.0 3.0 6.0 9.0 

Comments

0

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.

public static void main(String[] args) { int[][] ar = { {12, 33, 23}, {34, 56, 75}, {14, 76, 89}, {45, 87, 20}}; for (int[] num : ar) { for (int ele : num) { System.out.print(" " + ele); } System.out.println(" "); } } 

Output:

 12 33 23 34 56 75 14 76 89 45 87 20 

Comments

0

an alternative implementation that is not as fast as a classic 2-loops approach:

 System.out.println( Arrays.deepToString(board) .replaceAll("], ", "\n") .replaceAll("[\\[\\]\\,]", "") ); 

replace() calls are needed to transfrom

[[5, 3, 0], [6, 0, 0], [0, 9, 8]] 

into

5 3 0 6 0 0 0 9 8 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.