Wednesday, 15 January 2014

java - need help typing out a 2 dimensional array -



java - need help typing out a 2 dimensional array -

i trying type out 2 dimentional array in messagedialog using joptionpane. have tried not sure how it. have far.

where programme starts:

package p4; import javax.swing.joptionpane; import arrays.integer2darrays; public class exercise4b { public void testarray(int[][] array) { string message = ""; message += "tostring: " + integer2darrays.tostring( array ) + "\n"; // message += "elements: " + integer2darrays.elements( array ) + "\n"; // message += "max: " + integer2darrays.max( array ) + "\n"; // message += "min: " + integer2darrays.min( array ) + "\n"; // message += "sum: " + integer2darrays.sum( array ) + "\n"; // message += "average: " + string.format( "%1.2f", integer2darrays.average( array ) ) + "\n"; joptionpane.showmessagedialog( null, message ); } public static void main(string[] args) { exercise4b e4b = new exercise4b(); int[][] test1 = {{1,2,3,4},{-5,-6,-7,-18},{10,9,8,7}}; int[][] test2 = {{1,2,3,4,5,6},{-7,-8,-9},{2,5,8,11,8},{6,4}}; e4b.testarray(test1); e4b.testarray(test2); } }

where suposed create method converts array string.

bundle arrays; public class integer2darrays { public static string tostring(int[][] array){ } }

to display 2 dimensional array in simple fashion utilize method:

public class integer2darrays { public static string tostring(int[][] array){ stringbuilder sb = new stringbuilder(); for(int i=0;i<array.length;i++) { for(int j=0;j<array[i].length;j++) { sb.append(array[i][j]).append(", "); } sb.append("\n"); } homecoming sb.tostring(); } }

this produce output next way:

int[][] test1 = {{1,2,3,4},{-5,-6,-7,-18},{10,9,8,7}};

would be:

1, 2, 3, 4, -5, -6, -7, -18, 10, 9, 8, 7,

if want different form of output please specify format expect.

java arrays methods tostring

No comments:

Post a Comment