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
|1 2 3|
|4 5 6|
Use the code below to print the values.
System.out.println(Arrays.deepToString());
Output will look like this (the whole matrix in one line):
[[1,2,3],[4,5,6]]
@Ashika's answer works fantastically if you want (0,0) to be represented in the top, left corner, per normal CS convention. If however you would prefer to use normal mathematical convention and put (0,0) in the lower left hand corner, you could use this:
LinkedList<String> printList = new LinkedList<String>();
for (char[] row: array) {
printList.addFirst(Arrays.toString(row));;
}
while (!printList.isEmpty())
System.out.println(printList.removeFirst());
This used LIFO (Last In First Out) to reverse the order at print time.
There is nothing wrong with what you have. Double-nested for loops should be easily digested by anyone reading your code.
That said, the following formulation is denser and more idiomatic java. I'd suggest poking around some of the static utility classes like Arrays and Collections sooner than later. Tons of boilerplate can be shaved off by their efficient use.
for (int[] row : array)
{
Arrays.fill(row, 0);
System.out.println(Arrays.toString(row));
}
That's the best I guess:
for (int[] row : matrix){
System.out.println(Arrays.toString(row));
}
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));
Adapting from https://stackoverflow.com/a/49428678/1527469 (to add indexes):
System.out.print(" ");
for (int row = 0; row < array[0].length; row++) {
System.out.print("\t" + row );
}
System.out.println();
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[row].length; col++) {
if (col < 1) {
System.out.print(row);
System.out.print("\t" + array[row][col]);
} else {
System.out.print("\t" + array[row][col]);
}
}
System.out.println();
}