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

新手上路,请多包涵

我在使用二维数组时遇到问题。我有这样的显示:

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

原文由 kix 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 464
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 个。

原文由 Andrew Thompson 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

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

原文由 Marco Lackovic 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题