i am trying to type out a 2 dimentional array in a messagedialog using JOptionPane. I have tried but i am not sure how to do it. This is what i have so far.
Where my program 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 i am suposed to create a method that converts the array to a string.
package arrays;
public class Integer2dArrays {
public static String toString(int[][] array){
}
}
To display an two dimensional array in a simple fashion you could use this 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");
}
return sb.toString();
}
}
This will produce output the following 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 you want a different form of output please specify what format you expect.
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.