0

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 ??

1
  • 1
    Use System.out.printf(...) and use format specifiers, like %4d. Commented Mar 26, 2014 at 0:41

2 Answers 2

1

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()); 
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.