如何像表格一样打印二维数组

时间:2022-12-06 21:36:43

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

14 个解决方案

#1


9  

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.

当然,你也可以交换其他答案中提到的7和5,得到每行7。

#2


13  

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

您需要在每一行之后打印一行……打印("\n"),或使用println,等等。正如它所显示的那样,您只是在打印任何东西——System.out.print(""),将打印替换为ln或"\n"。

#3


10  

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

您可以编写一个方法来打印2d数组,如下所示:

//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();
    }
}

#4


8  

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

如果你不介意逗号和括号,你可以简单地使用:

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

#5


3  

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.

作为@djechlin回答的一部分,您应该更改行和列。因为你有7行5列,但实际上你想要7列5行。

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

#6


3  

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:

正如@djechlin充分解释的那样,从最初的问题中我们可以看出,在完成表的每一行之后,都需要打印新的行。所以,我们需要这样的表述:

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!

这是一个范围问题。注意,有两个循环是有原因的——一个循环处理行,而另一个循环处理列。内部循环“j”循环遍历给定的“i”的每个数组元素“j”。因此,在j循环的末尾,应该有一行。您可以将这个“j”循环的每个迭代看作构建表的“列”。由于内循环构建了我们的列,所以我们不想在那里打印行—它将为每个元素创建新的行!

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.

一旦脱离了j循环,就需要在继续进行下一个“i”迭代之前终止这一行。这是处理新行的正确位置,因为它是表行的“范围”,而不是表的列。

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.

你可以看到,这条新线是成立的,即使你通过改变"i"和"j"循环的结束值来改变表格的维度。

#7


2  

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

仅就记录而言,Java 8提供了更好的替代方法。

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")));

#8


2  

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

更有效、更简单的方式打印2D数组格式:

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

#9


0  

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")));

System.out.println(Arrays.deepToString(矩阵).replace(“,”,“\ n”)));

#10


0  

Iliya,

亲戚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 |
----------------------

#11


-1  

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.

这可能有点让人困惑,因为我用我的语言来命名元素/变量,但是CBA来翻译它们,对不起。

#12


-1  

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.

#13


-1  

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.

这样可以在行的循环中添加一条新的行。当第一行完成打印时,代码将在新行中跳转。

#14


-2  

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

你们所有人,请注意,我很惊讶,它需要一点点的智商,只是得到长度的arr[0]。长度和问题解决了

   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();
    }

#1


9  

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.

当然,你也可以交换其他答案中提到的7和5,得到每行7。

#2


13  

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

您需要在每一行之后打印一行……打印("\n"),或使用println,等等。正如它所显示的那样,您只是在打印任何东西——System.out.print(""),将打印替换为ln或"\n"。

#3


10  

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

您可以编写一个方法来打印2d数组,如下所示:

//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();
    }
}

#4


8  

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

如果你不介意逗号和括号,你可以简单地使用:

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

#5


3  

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.

作为@djechlin回答的一部分,您应该更改行和列。因为你有7行5列,但实际上你想要7列5行。

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

#6


3  

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:

正如@djechlin充分解释的那样,从最初的问题中我们可以看出,在完成表的每一行之后,都需要打印新的行。所以,我们需要这样的表述:

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!

这是一个范围问题。注意,有两个循环是有原因的——一个循环处理行,而另一个循环处理列。内部循环“j”循环遍历给定的“i”的每个数组元素“j”。因此,在j循环的末尾,应该有一行。您可以将这个“j”循环的每个迭代看作构建表的“列”。由于内循环构建了我们的列,所以我们不想在那里打印行—它将为每个元素创建新的行!

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.

一旦脱离了j循环,就需要在继续进行下一个“i”迭代之前终止这一行。这是处理新行的正确位置,因为它是表行的“范围”,而不是表的列。

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.

你可以看到,这条新线是成立的,即使你通过改变"i"和"j"循环的结束值来改变表格的维度。

#7


2  

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

仅就记录而言,Java 8提供了更好的替代方法。

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")));

#8


2  

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

更有效、更简单的方式打印2D数组格式:

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

#9


0  

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")));

System.out.println(Arrays.deepToString(矩阵).replace(“,”,“\ n”)));

#10


0  

Iliya,

亲戚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 |
----------------------

#11


-1  

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.

这可能有点让人困惑,因为我用我的语言来命名元素/变量,但是CBA来翻译它们,对不起。

#12


-1  

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.

#13


-1  

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.

这样可以在行的循环中添加一条新的行。当第一行完成打印时,代码将在新行中跳转。

#14


-2  

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

你们所有人,请注意,我很惊讶,它需要一点点的智商,只是得到长度的arr[0]。长度和问题解决了

   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();
    }