简体   繁体   中英

How to print a 2D array to matrix format

My Code so far is below....

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

with the output being:

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,

but i need it to look like this...

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

how do i fix this ??

You can try adding some print statements:

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

Demo:

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

Note: You can also use a 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());

Just use this, it is all you need.

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

Remember to add following : import java.util.Arrays;


If you insist on output exactly as you write, you can do following

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

But there remains comma on last line, so if you do not want it there, you have to check it

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM