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));
Answer from Prabhakaran Ramaswamy on Stack OverflowYou 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));
I would prefer generally foreach when I don't need making arithmetic operations with their indices.
for (int[] x : array)
{
for (int y : x)
{
System.out.print(y + " ");
}
System.out.println();
}
[Java] Printing out a row in a 2d array
java - Printing a 2D array - Code Review Stack Exchange
How to print a 2-D array with initial values in a table-like ...
Print 2D color array with boxes
Videos
Tried printing out the rows in a 2d matrix using this code:
class Main {
public static void main(String args[]) {
int[][]matrix = { {1,2,3},
{4,5,6},
{7,8,9},
{1,2,1} };
for(int[] row: matrix){
System.out.println(row);
}
}
}It doesn't work. I get this on the compiler:
[I@76ed5528 [I@2c7b84de [I@3fee733d [I@5acf9800
What's going on?
Coding enhancement
public static int[][] getArray(){
return new int[5][6]; // no need of intermediate object
}
Optimizing speed : never have a computation or an evaluation at each loop, car be very heavy with great number
for(int i = 0, n = array.lenght; i < n ; i++) { ..
as init_array return array you can write directly :
printArray(init_array(getArray()));
Use :
System.getProperty("line.separator");for all OSStringBuilderthen print out :
.
public static void printArray(int[][] array){
String NEWLINE = System.getProperty("line.separator"); // You can put it 'public static' elsewhere
StringBuilder sb = new StringBuilder(); // you can give the size of it between ()
for(int i = 0; i< array.length;i++)
for(int j =0; j< array[i].length;j++)
sb.append(array[i][j])
sb.append(NEWLINE);
}
}
System.out.println(sb.toString());
}
You need to read input (from the command line) using the Scanner class for the dimensions of the array. In this line, you chose 5 and 6:
int[][] array = new int[5][6];
Everything looks good except for that method (getArray). In that method, you should read in two numbers from the command line, and use those numbers (instead of 5 and 6) as the dimensions of the array.