[java] 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("");}
        }

This question is related to java arrays text format

The answer is


I'll post a solution with a bit more elaboration, in addition to code, as the initial mistake and the subsequent ones that have been demonstrated in comments are common errors in this sort of string concatenation problem.

From the initial question, as has been adequately explained by @djechlin, we see that there is the need to print a new line after each line of your table has been completed. So, we need this statement:

System.out.println();

However, printing that immediately after the first print statement gives erroneous results. What gives?

1 
2 
...
n 

This is a problem of scope. Notice that there are two loops for a reason -- one loop handles rows, while the other handles columns. Your inner loop, the "j" loop, iterates through each array element "j" for a given "i." Therefore, at the end of the j loop, you should have a single row. You can think of each iterate of this "j" loop as building the "columns" of your table. Since the inner loop builds our columns, we don't want to print our line there -- it would make a new line for each element!

Once you are out of the j loop, you need to terminate that row before moving on to the next "i" iterate. This is the correct place to handle a new line, because it is the "scope" of your table's rows, instead of your table's columns.

for(i=0;i<7;i++){
    for(j=0;j<5;j++) {
        System.out.print(twoDm[i][j]+" ");  
    }
    System.out.println();
}

And you can see that this new line will hold true, even if you change the dimensions of your table by changing the end values of your "i" and "j" loops.


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

System.out.println(Arrays.deepToString(twoDm).replace("], ", "]\n"));

Just for the records, Java 8 provides a better alternative.

int[][] table = new int[][]{{2,4,5},{6,34,7},{23,57,2}};

System.out.println(Stream.of(table)
    .map(rowParts -> Stream.of(rowParts
    .map(element -> ((Integer)element).toString())
        .collect(Collectors.joining("\t")))
    .collect(Collectors.joining("\n")));

ALL OF YOU PLEASE LOOT AT IT I Am amazed it need little IQ just get length by arr[0].length and problem solved

   for (int i = 0; i < test.length; i++) {
        for (int j = 0; j < test[0].length; j++) {

        System.out.print(test[i][j]);
    }
        System.out.println();
    }

For traversing through a 2D array, I think the following for loop can be used.

        for(int a[]: twoDm)
        {
            System.out.println(Arrays.toString(a));
        }
if you don't want the commas you can string replace
if you want this to be performant you should loop through a[] and then print it.

You can creat a method that prints the matrix as a table :

Note: That does not work well on matrices with numbers with many digits and non-square matrices.

    public static void printMatrix(int size,int row,int[][] matrix){

            for(int i = 0;i <  7 * size ;i++){ 
                  System.out.print("-");    
            }
                 System.out.println("-");

            for(int i = 1;i <= matrix[row].length;i++){
               System.out.printf("| %4d ",matrix[row][i - 1]);
             }
               System.out.println("|");


                 if(row == size -  1){

             // when we reach the last row,
             // print bottom line "---------"

                    for(int i = 0;i <  7 * size ;i++){ 
                          System.out.print("-");
                     }
                          System.out.println("-");

                  }
   }

  public static void main(String[] args){

     int[][] matrix = {

              {1,2,3,4},
              {5,6,7,8},
              {9,10,11,12},
              {13,14,15,16}


      };

       // print the elements of each row:

     int rowsLength = matrix.length;

          for(int k = 0; k < rowsLength; k++){

              printMatrix(rowsLength,k,matrix);
          }


  }

Output :

---------------------
|  1 |  2 |  3 |  4 |
---------------------
|  5 |  6 |  7 |  8 |
---------------------
|  9 | 10 | 11 | 12 |
---------------------
| 13 | 14 | 15 | 16 |
---------------------

I created this method while practicing loops and arrays, I'd rather use:

System.out.println(Arrays.deepToString(matrix).replace("], ", "]\n")));


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


More efficient and easy way to print the 2D array in a formatted way:

Try this:

public static void print(int[][] puzzle) {
        for (int[] row : puzzle) {
            for (int elem : row) {
                System.out.printf("%4d", elem);
            }
            System.out.println();
        }
        System.out.println();
    }

Sample Output:

   0   1   2   3
   4   5   6   7
   8   9  10  11
  12  13  14  15

You could write a method to print a 2d array like this:

//Displays a 2d array in the console, one line per row.
static void printMatrix(int[][] grid) {
    for(int r=0; r<grid.length; r++) {
       for(int c=0; c<grid[r].length; c++)
           System.out.print(grid[r][c] + " ");
       System.out.println();
    }
}

A part from @djechlin answer, you should change the rows and columns. Since you are taken as 7 rows and 5 columns, but actually you want is 7 columns and 5 rows.

Do this way:-

int twoDm[][]= new int[5][7];

for(i=0;i<5;i++){
    for(j=0;j<7;j++) {
        System.out.print(twoDm[i][j]+" ");
    }
    System.out.println("");
}

Declared a 7 by 5 array which is similar to yours, with some dummy data. Below should do.

    int[][] array = {{21, 12, 32, 14, 52}, {43, 43, 55, 66, 72}, {57, 64, 52, 57, 88},{52, 33, 54, 37, 82},{55, 62, 35, 17, 28},{55, 66, 58, 72, 28}}; 
    
    for (int i = 0; i < array.length; i++) {
        for (int j = 0; j < array[i].length; j++) {
            System.out.print(array[i][j] + " ");
        }
        System.out.println(); // the trick is here, print a new line after iterating first row.
    }

Iliya,

Sorry for that.

you code is work. but its had some problem with Array row and columns

here i correct your code this work correctly, you can try this ..

public static void printMatrix(int size, int row, int[][] matrix) {

    for (int i = 0; i < 7 * matrix[row].length; i++) {
        System.out.print("-");
    }
    System.out.println("-");

    for (int i = 1; i <= matrix[row].length; i++) {
        System.out.printf("| %4d ", matrix[row][i - 1]);
    }
    System.out.println("|");

    if (row == size - 1) {

        // when we reach the last row,
        // print bottom line "---------"

        for (int i = 0; i < 7 * matrix[row].length; i++) {
            System.out.print("-");
        }
        System.out.println("-");

    }
}

public static void length(int[][] matrix) {

    int rowsLength = matrix.length;

    for (int k = 0; k < rowsLength; k++) {

        printMatrix(rowsLength, k, matrix);

    }

}

public static void main(String[] args) {

    int[][] matrix = { { 1, 2, 5 }, { 3, 4, 6 }, { 7, 8, 9 }

    };

    length(matrix);

}

and out put look like

----------------------
|    1 |    2 |    5 |
----------------------
|    3 |    4 |    6 |
----------------------
|    7 |    8 |    9 |
----------------------

public static void main(String[] args) {
    int[][] matrix = { 
                       { 1, 2, 5 }, 
                       { 3, 4, 6 },
                       { 7, 8, 9 } 
                     };

    System.out.println(" ** Matrix ** ");

    for (int rows = 0; rows < 3; rows++) {
        System.out.println("\n");
        for (int columns = 0; columns < matrix[rows].length; columns++) {
            System.out.print(matrix[rows][columns] + "\t");
        }
    }
}

This works,add a new line in for loop of the row. When the first row will be done printing the code will jump in new line.


This might be late however this method does what you ask in a perfect manner, it even shows the elements in ' table - like ' style, which is brilliant for beginners to really understand how an Multidimensional Array looks.

public static void display(int x[][])   // So we allow the method to take as input Multidimensional arrays
    {
        //Here we use 2 loops, the first one is for the rows and the second one inside of the rows is for the columns
        for(int rreshti = 0; rreshti < x.length; rreshti++)     // Loop for the rows
        {
            for(int kolona = 0; kolona < x[rreshti].length;kolona++)        // Loop for the columns
            {
                System.out.print(x[rreshti][kolona] + "\t");            // the \t simply spaces out the elements for a clear view   
            }
            System.out.println();   // And this empty outputprint, simply makes sure each row (the groups we wrote in the beggining in seperate {}), is written in a new line, to make it much clear and give it a table-like look 
        }
    }

After you complete creating this method, you simply put this into your main method:

display(*arrayName*); // So we call the method by its name, which can be anything, does not matter, and give that method an input (the Array's name)

NOTE. Since we made the method so that it requires Multidimensional Array as a input it wont work for 1 dimensional arrays (which would make no sense anyways)

Source: enter link description here

PS. It might be confusing a little bit since I used my language to name the elements / variables, however CBA to translate them, sorry.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to text

Difference between opening a file in binary vs text How do I center text vertically and horizontally in Flutter? How to `wget` a list of URLs in a text file? Convert txt to csv python script Reading local text file into a JavaScript array Python: How to increase/reduce the fontsize of x and y tick labels? How can I insert a line break into a <Text> component in React Native? How to split large text file in windows? Copy text from nano editor to shell Atom menu is missing. How do I re-enable

Examples related to format

Brackets.io: Is there a way to auto indent / format <html> Oracle SQL - DATE greater than statement What does this format means T00:00:00.000Z? How to format date in angularjs How do I change data-type of pandas data frame to string with a defined format? How to pad a string to a fixed length with spaces in Python? How to format current time using a yyyyMMddHHmmss format? java.util.Date format SSSSSS: if not microseconds what are the last 3 digits? Formatting a double to two decimal places How enable auto-format code for Intellij IDEA?