Java数组矩阵编号

时间:2017-03-25 19:53:21

标签: java arrays matrix

这是我制作的代码

class Printsqu {
    public static void main(String[] args) {
        int[][] array = { { 1,5,9,13 }, { 2,6,10,14 }, { 3,7,11,15 },
                { 4,8,12,16 }, };

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

输出应为

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

这个但打印出来

1593
261014
371115
481216

所以我在它们之间添加\但它跳得太多了。

有什么方法可以解决这个问题吗?

有趣的是,数字之间的空间是不同的

如果你们想要提供有关代码和解释的详细信息,我将不胜感激。

2 个答案:

答案 0 :(得分:2)

试试这个

public static void main(String[] args) {
    int[][] array = { { 1,5,9,13 }, { 2,6,10,14 }, { 3,7,11,15 },
            { 4,8,12,16 }, };

    for (int i = 0; i < array.length; i++) {
        for (int j = 0; j < array[i].length; j++) {

            System.out.printf("%2d ", array[i][j]);
        }
        System.out.println();
    }
}

答案 1 :(得分:1)

WIDTH的值替换为您想为一个数字提供的任意数量的字符。

class Printsqu {
  public static final int WIDTH = 3;
  public static void main(String[] args){
    int[][] array = { { 1,5,9,13 }, { 2,6,10,14 }, { 3,7,11,15 },
                { 4,8,12,16 }, };

        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                System.out.printf("%"+WIDTH+"d", array[i][j]);
            }
            System.out.println();
        }
  }
}