How to print Two-Dimensional Array like table
You need to print a new line after each row... System.out.print("\n")
, or use println
, etc. As it stands you are just printing nothing - System.out.print("")
, replace print
with println
or ""
with "\n"
.
public class FormattedTablePrint {
public static void printRow(int[] row) {
for (int i : row) {
System.out.print(i);
System.out.print("\t");
}
System.out.println();
}
public static void main(String[] args) {
int twoDm[][]= new int[7][5];
int i,j,k=1;
for(i=0;i<7;i++) {
for(j=0;j<5;j++) {
twoDm[i][j]=k;
k++;
}
}
for(int[] row : twoDm) {
printRow(row);
}
}
}
Output
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
26 27 28 29 30
31 32 33 34 35
Of course, you might swap the 7 & 5 as mentioned in other answers, to get 7 per row.
If you don't mind the commas and the brackets you can simply use:
System.out.println(Arrays.deepToString(twoDm).replace("], ", "]\n"));