print matrix in dialog box
I'm having a little difficulty to print a matrix array on dialog box. The matrix is integer and as far as i understood i need to change it into string?
anyway, here's the code:
public void print_Matrix(int row, int column)
{
for (int i = 0; i <= row; i++)
{
for (int j = 0; j <= column; j++)
{
JOptionPane.showMessageDialog(null, matrix_Of_Life);
}
}
what I need to do in order to print array in开发者_开发百科to dialog box?
thanks.
For small 2D arrays, something like this is convenient:
int[][] matrix = {{1,2,3}, {4,5,6}, {7,8,9}};
String s = Arrays.deepToString(matrix)
.replace("], ", "\n").replaceAll(",|\\[|\\]", "");
System.out.println(s);
This prints:
1 2 3
4 5 6
7 8 9
This concedes control and speed for clarity and conciseness. If your matrix is larger and/or you want complete control on how each element is printed (e.g. right alignment), you'd probably have to do something else.
private static void printMatrix(char[][] mat) {
StringBuffer str = new StringBuffer();
for(int i=0;i<mat.length;i++){
for(int j=0; j<mat[0].length;j++){
str.append(mat[i][j]).append(" ");
}
str.append("\n");
}
System.out.println(str.toString());
}
StringBuffer str=new StringBuffer();
for(i=0;i<3;i++)
{
for(j=0;j<3;j++){
str.append(matrix[i][j]).str(" ");
}
str.append("\n");
}
JOptionPane.showMessageDialog(null,"Matrix:"+"\n" +str);
精彩评论