Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print Two-Dimensional Array like table

I'm having a problem with two dimensional array. I'm having a display like this:

1 2 3 4 5 6 7 9 10 11 12 13 14 15 16 . . . etc

What basically I want is to display to display it as:

1 2 3 4 5 6     7  
8 9 10 11 12 13 14  
15 16 17 18 19 20  
21 22 23 24 ... etc

Here is my code:

    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(i=0;i<7;i++){
            for(j=0;j<5;j++) {
                System.out.print(twoDm[i][j]+" ");
                System.out.print("");}
        }
like image 259
kix Avatar asked Oct 11 '12 17:10

kix


People also ask

Is a 2D array a table?

The two dimensional (2D) array in C programming is also known as matrix. A matrix can be represented as a table of rows and columns.

How do you print a multi dimensional array?

To print a multi-dimensional array, you instead need to call the Arrays. deepToString() method and pass the multi-dimensional array as an argument.


3 Answers

If you don't mind the commas and the brackets you can simply use:

System.out.println(Arrays.deepToString(twoDm).replace("], ", "]\n"));
like image 78
Marco Lackovic Avatar answered Oct 04 '22 08:10

Marco Lackovic


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.

like image 20
Andrew Thompson Avatar answered Oct 04 '22 09:10

Andrew Thompson


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".

like image 21
djechlin Avatar answered Oct 04 '22 07:10

djechlin