17

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

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

15 回答 15

24

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

System.out.println(Arrays.deepToString(twoDm).replace("], ", "]\n"));
于 2013-07-02T10:38:37.493 回答
13

您需要在每一行之后打印一个新行... System.out.print("\n"),或使用等。println就目前而言,您只是不打印任何内容 - System.out.print(""),替换printprintln"""\n"

于 2012-10-11T17:30:34.417 回答
13
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 个。

于 2012-10-11T18:03:49.473 回答
11

您可以编写一个方法来打印这样的二维数组:

//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();
    }
}
于 2012-10-11T17:33:48.483 回答
3

@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("");
}
于 2012-10-11T17:31:42.577 回答
3

除了代码之外,我将发布一个更详细的解决方案,因为最初的错误和注释中已经证明的后续错误是此类字符串连接问题中的常见错误。

从最初的问题开始,正如@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”循环的最终值来更改表格的尺寸。

于 2012-10-11T18:05:55.603 回答
3

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

试试这个:

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
于 2016-04-15T19:12:55.183 回答
2

仅作记录,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")));
于 2015-09-30T15:12:32.580 回答
1

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

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

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

于 2017-08-14T10:55:52.693 回答
1

伊利亚,

对此感到抱歉。

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

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

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 |
----------------------
于 2018-05-24T06:40:58.103 回答
1

声明了一个与您的类似的 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.
    }
于 2020-11-07T11:51:19.160 回答
-1

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

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)

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

来源:在此处输入链接描述

PS。由于我使用我的语言来命名元素/变量,但是 CBA 来翻译它们,抱歉,这可能有点令人困惑。

于 2015-08-26T09:47:10.903 回答
-2
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 循环中添加一个新行。当第一行打印完成时,代码将跳转到新行。

于 2016-10-29T07:36:01.117 回答
-2
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.
于 2017-01-13T17:28:01.773 回答
-3

你们所有人都请掠夺它我很惊讶它只需要很少的智商就可以通过 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-11-16T03:30:41.760 回答