Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Best way to print 2D array? [closed]

I was wondering what the best way of printing a 2D array was. This is some code that I have and I was just wondering if this is good practice or not. Also correct me in any other mistakes I made in this code if you find any. Thanks!

int rows = 5; int columns = 3;  int[][] array = new int[rows][columns];  for(int i = 0; i<rows; i++)     for(int j = 0; j<columns; j++)         array[i][j] = 0;  for(int i = 0; i<rows; i++) {     for(int j = 0; j<columns; j++)     {         System.out.print(array[i][j]);     }     System.out.println(); } 
like image 260
Chip Goon Lewin Avatar asked Oct 29 '13 01:10

Chip Goon Lewin


People also ask

Can you print a 2D array in Java?

Java provides multiple ways to print a 2d array, for example nested for-loop, for-each loop, Arrays. deepToString() method, etc.

How do you print a two-dimensional array?

public class Print2DArray { public static void main(String[] args) { final int[][] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; for (int i = 0; i < matrix. length; i++) { //this equals to the row in our matrix. for (int j = 0; j < matrix[i].

How do I print a 2D array using toString?

toString() method. We know that a two-dimensional array in Java is a single-dimensional array having another single-dimensional array as its elements. We can use the Arrays. toString() method to print string representation of each single-dimensional array in the given two-dimensional array.


1 Answers

You can print in simple way.

Use below to print 2D array

int[][] array = new int[rows][columns]; System.out.println(Arrays.deepToString(array)); 

Use below to print 1D array

int[] array = new int[size]; System.out.println(Arrays.toString(array)); 
like image 58
Prabhakaran Ramaswamy Avatar answered Sep 28 '22 04:09

Prabhakaran Ramaswamy