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

kix*_*kix 14 java arrays format text

我有二维数组的问题.我有这样的显示:

1 2 3 4 5 6 7 9 10 11 12 13 14 15 16 . . . etc
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

    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("");}
        }
Run Code Online (Sandbox Code Playgroud)

dje*_*lin 13

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

  • 他说要在每次行之后放置'println()`,而不是在每次打印之后.换句话说,在执行第二个`for()`循环之后但允许第一个循环之前. (2认同)
  • 确保您的println在正确的范围内.你的第一个print语句连接同一行的所有内容,因此你需要确保你的换行符发生在"j"for循环的范围之外. (2认同)

Mar*_*vic 12

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

System.out.println(Arrays.deepToString(twoDm).replace("], ", "]\n")));
Run Code Online (Sandbox Code Playgroud)

  • 简单,不需要额外的依赖.谢谢! (3认同)

Tho*_*orn 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();
    }
}
Run Code Online (Sandbox Code Playgroud)


And*_*son 10

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

产量

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  
Run Code Online (Sandbox Code Playgroud)

当然,你可以像其他答案中提到的那样交换7和5,每行7个.