簡體   English   中英

如何像表格一樣打印二維數組

[英]How to print Two-Dimensional Array like table

我有二維數組的問題。 我有這樣的顯示器:

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

如果您不介意逗號和括號,您可以簡單地使用:

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

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

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。

您可以編寫一個方法來打印這樣的二維數組:

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

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

除了代碼之外,我將發布一個更詳細的解決方案,因為最初的錯誤和在注釋中證明的后續錯誤是此類字符串連接問題中的常見錯誤。

從最初的問題開始,正如@djechlin 已經充分解釋的那樣,我們看到需要在表格的每一行完成后打印一個新行。 所以,我們需要這樣的聲明:

System.out.println();

但是,在第一個打印語句之后立即打印會給出錯誤的結果。 是什么賦予了?

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”循環的結束值來更改表的尺寸,這條新行也將成立。

以格式化方式打印二維數組的更有效和簡單的方法:

試試這個:

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

只是為了記錄,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")));

伊利亞,

對不起。

你的代碼是工作。 但它的數組行和列有一些問題

在這里,我更正了您的代碼,使其正常工作,您可以試試這個..

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

您可以創建一個將矩陣打印為表格的方法:

注意:這不適用於具有多位數字和非方陣的數字矩陣。

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

聲明了一個 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.
    }

這可能晚了但是這種方法以完美的方式完成了您的要求,它甚至以“類似表格”的樣式顯示元素,這對於初學者真正了解多維數組的外觀非常有用。

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

完成此方法的創建后,只需將其放入主方法中即可:

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)

筆記。 由於我們制作了該方法,因此它需要多維數組作為輸入,因此它不適用於一維數組(無論如何都沒有意義)

來源:在此處輸入鏈接描述

附注。 由於我使用我的語言來命名元素/變量,因此可能會有點混亂,但是 CBA 來翻譯它們,抱歉。

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 循環中添加一個新行。 當第一行完成打印時,代碼將跳入新行。

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.

你們所有人都請掠奪它我很驚訝它只需要很少的智商就可以通過 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();
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM