如何将2D数组打印为矩阵格式

时间:2014-03-26 00:39:10

标签: java

到目前为止我的代码低于......

int [][] out = readGrayscaleImage("robbie_robot.jpg");
    for (int x = 0; x < out.length; x++) {
            System.out.println();
            for (int y = 0; y < out[0].length; y++) {
                System.out.print(out[x][y]);
                System.out.print(", ");
            }
    }

输出为:

255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 
255, 255, 255, 255, 156, 156, 255, 255, 255, 255, 
255, 254, 244, 0, 88, 88, 0, 244, 255, 255, 
255, 255, 255, 208, 39, 39, 184, 255, 255, 255, 
254, 255, 254, 197, 40, 36, 197, 255, 255, 255,

但我需要它看起来像这样......

{255, 255, 255, 255, 255, 254, 255, 255, 255, 255}, 
{255, 255, 255, 255, 156, 156, 255, 255, 255, 255}, 
{255, 254, 244, 0, 88, 88, 0, 244, 255, 255}.
{255, 255, 255, 208, 39, 39, 184, 255, 255, 255}, 
{254, 255, 254, 197, 40, 36, 197, 255, 255, 255}

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

您可以尝试添加一些打印语句:

int[][] out = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

for (int x = 0; x < out.length; x++) {
    System.out.print("{");
    for (int y = 0; y < out[0].length; y++) {
        System.out.print(out[x][y] + ",");
    }
    if (x != out.length - 1) {
        System.out.println("},");
    } else {
        System.out.println("}");
    }
}

<强>演示:

{1,2,3,},
{4,5,6,},
{7,8,9,}

注意:您还可以使用StringBuilder

int[][] out = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
StringBuilder sb = new StringBuilder();

for (int x = 0; x < out.length; x++) {
    sb.append("{");
    for (int y = 0; y < out[0].length; y++) {
        sb.append(out[x][y]).append(",");
    }
    sb.append("},\n");
}
sb.deleteCharAt(sb.length() - 1).deleteCharAt(sb.length() - 1);

System.out.println(sb.toString());

答案 1 :(得分:1)

只需使用它,这就是你所需要的。

    for (int[] out1 : out) {
        Arrays.toString(out1);
    }

请务必添加以下内容:import java.util.Arrays;


如果您坚持输出与写作完全一致,则可以执行以下操作

    for (int[] out1 : out) {
        System.out.print(Arrays.toString(out1).replaceAll("\\[", "{").replaceAll("\\]", "}"));
    }

但最后一行仍然有逗号,所以如果你不想在那里,你必须检查它

    for (int[] out1 : out) {
        System.out.print(Arrays.toString(out1).replaceAll("\\[", "{").replaceAll("\\]", "}"));
        if (out1 != out[out.length-1]){
            System.out.print(",");
        }
        System.out.println("");
    }