【问题标题】:How to print Two-Dimensional Array like table如何像表格一样打印二维数组
【发布时间】:2012-10-11 17:29:29
【问题描述】:

我遇到了二维数组的问题。我有这样的显示:

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

基本上我想要的是将其显示为:

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

这是我的代码:

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

【问题讨论】:

    标签: java arrays text format


    【解决方案1】:

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

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

    【讨论】:

    • 简单好用,不需要额外的依赖。谢谢!
    【解决方案2】:
    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);
            }
        }
    }
    

    输出

    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  
    

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

    【讨论】:

    • 如果第 i 个第 j 个元素的位数比第 i 个 +-1 和第 j 个元素多得多,会发生什么?
    • 有没有办法使用printf,这样我就可以打印一个可变大小的字符串表并且仍然对齐行/列? (例如,数组可能是{{"bat","stegosaurus","turtle"}, {"horse", "armadillo", "cow"}})
    【解决方案3】:

    您需要在每一行之后打印一个新行...System.out.print("\n"),或使用println,等等。就目前而言,您什么都没有打印 - System.out.print(""),将print 替换为println 或"" 和 "\n"。

    【讨论】:

    • 我刚刚更换了它,现在我有并输出如下:1 2 3 5 6 7 8 等,但它只是垂直的。我想要的是一张桌子。无论如何,谢谢你的回复。
    • 他说要把println()放在每一行之后,而不是在你每次打印之后。换句话说,在执行第二个for() 循环之后,但在允许第一个循环之前。
    • 确保您的 println 在正确的范围内。您的第一个 print 语句将同一行上的所有内容连接起来,因此您需要确保您的换行符发生在“j”for 循环的范围之外。
    • 顺便说一句。我应该如何让它像先打印 1-7 然后再打印 8-14 等等。我真的很难理解这一点。
    • @kix:你试过我的answer。
    【解决方案4】:

    您可以编写一个打印二维数组的方法,如下所示:

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

    【讨论】:

    • 这也许是我需要的。我会试试这个,稍后在这里发布输出。谢谢!
    【解决方案5】:

    来自 @djechlin 答案的一部分,您应该更改行和列。由于您被视为 7 行 5 列,但实际上您想要的是 7 列和 5 行。

    这样做:-

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

    【讨论】:

    • 是的,伙计。现在我有异常 ArrayIndexOutOfBoundsException。
    • @kix:根据您的期望使用数组声明更新了我的答案。 int twoDm[][]= new int[5][7];
    • 巨魔一定在工作。我看不出你的回答有什么问题。
    • @Siva Charan - 它现在正在工作,但仍显示在 1 行中。我想要的是在不使用网格的情况下以 5 行显示它。谢谢!
    • @sircapsalot - 不。我刚刚将数组声明为 [7][5]。呵呵,我只是个初学者。
    【解决方案6】:

    除了代码之外,我将发布一个更详细的解决方案,因为最初的错误以及在 cmets 中演示的后续错误是此类字符串连接问题中的常见错误。

    从最初的问题开始,正如@djechlin 充分解释的那样,我们看到需要在表格的每一行完成后打印一个新行。所以,我们需要这样的声明:

    System.out.println();
    

    但是,在第一个 print 语句之后立即打印会产生错误的结果。什么给了?

    1 
    2 
    ...
    n 
    

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

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

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

    并且您可以看到这条新行将成立,即使您通过更改“i”和“j”循环的最终值来更改表格的尺寸。

    【讨论】:

    • 这段代码是否也正确for(i=0;i&lt;5;i++){ for(j=0;j&lt;7;j++){ if (twoDm[i][j]%7==1) System.out.print("\n"); System.out.print(twoDm[i][j]+" ");
    • @Kix 不完全是。不过,这是一个简单的修复——只需将第二个 print 语句移到内部循环内。你不能在内部 for 循环之外调用单个单元格,因为你会得到一个越界异常。它会在你更正之后编译,但它会很混乱,因为你的输出之前会有一个空行。查看你的循环应该做什么,并重新排列你的行以获得你想要的格式。
    【解决方案7】:

    更多高效简单的方法以格式化方式打印二维数组:

    试试这个:

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

    样本输出:

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

    【讨论】:

      【解决方案8】:

      仅作记录,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")));
      

      【讨论】:

        【解决方案9】:

        您可以创建一个将矩阵打印为表格的方法:

        注意:这不适用于具有多位数字的矩阵和 非方阵。

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

        输出:

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

        我在练习循环和数组时创建了这个方法,我宁愿使用:

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

        【讨论】:

          【解决方案10】:

          伊利亚,

          对不起。

          你的代码是有效的。但它对数组行和列有一些问题

          我在这里更正了你的代码,它可以正常工作,你可以试试这个..

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

          输出看起来像

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

          【讨论】:

            【解决方案11】:

            声明了一个与您的类似的 7 x 5 数组,其中包含一些虚拟数据。下面应该做。

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

            【讨论】:

              【解决方案12】:
              public class class1 {
                  public static void main(String[] args){
                      int[][] a={{1, 2, 3}, {4, 5, 6}};
                      
                      for (int i = 0; i< a.length; i++){
                          System.out.print("Row" + (i + 1) + ": ");
                          for (int j = 0; j < a[i].length; j++){
                              System.out.print(a[i][j] + " ");
                          }
                          System.out.println();
                      }
                  }
              }
              

              结果:

              Row1: 1 2 3                                                                                          
              Row2: 4 5 6
              

              【讨论】:

                【解决方案13】:

                这可能会迟到,但是这种方法可以完美地满足您的要求,它甚至以“表格”样式显示元素,这对于初学者真正了解多维数组的外观非常有用。

                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 
                        }
                    }
                

                在你创建完这个方法之后,你只需把它放到你的 main 方法中:

                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)
                

                注意。由于我们制作的方法需要多维数组作为输入,因此它不适用于一维数组(无论如何这都没有意义)

                来源:enter link description here

                PS。由于我使用我的语言来命名元素/变量,因此可能会有点混乱,但是 CBA 来翻译它们,对不起。

                【讨论】:

                  【解决方案14】:
                  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.
                  

                  【讨论】:

                  • 请尝试在您的回答中提供上下文。一个独立的答案可能会解决这个特定场景中的问题,但一个解释可能会解决许多未来的问题。尝试包括您认为导致问题的原因以及为什么您的答案会解决问题。
                  【解决方案15】:
                  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");
                          }
                      }
                  }
                  

                  这行得通,在该行的 for 循环中添加一个新行。当第一行打印完成时,代码将跳转到新行。

                  【讨论】:

                  • 这基本上是 Andrew Thompson 的 answer 已经做到的。
                  【解决方案16】:

                  你们所有人都请掠夺它我很惊讶它需要很少的智商 只需通过 arr[0].length 获取长度即可解决问题

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

                  【讨论】:

                  • 这个答案真的是多余的。这基本上是现有答案的一个更糟糕的版本,因为它不会在每行中的数字之间添加间距。
                  猜你喜欢
                  • 2016-02-12
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2018-05-26
                  • 1970-01-01
                  • 2023-03-04
                  相关资源
                  最近更新 更多