2010-03-29 75 views
2

我在對話框中打印矩陣數組有點困難。 矩陣是整數,據我瞭解,我需要將其更改爲字符串?對話框中的打印矩陣

總之,這裏的代碼:

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

我需要什麼才能打印陣列到對話框呢?

謝謝。

+0

是什麼matrix_Of_Life樣子?它是一個多維數組嗎? – Ham 2010-03-29 06:52:40

+0

public void set_Matrix(int row,int column) \t { \t \t matrix_Of_Life = new int [row] [column]; \t \t \t \t \t \t Random randomGenerator = new Random(); \t \t對(INT I = 0;我<=行-1; ++ⅰ) \t \t { \t \t \t對(INT J = 0;Ĵ<=列1; ++ j)的 \t \t \t { \t \t \t \t int randomInt = randomGenerator.nextInt(2); \t \t \t //對於隨機結果「0」或「1」 \t \t \t System.out.println(「Generated:」+ randomInt); \t \t \t} \t \t} \t} – firestruq 2010-03-29 08:05:19

回答

2

對於小二維數組,像這樣是方便的:

int[][] matrix = {{1,2,3}, {4,5,6}, {7,8,9}}; 
String s = Arrays.deepToString(matrix) 
    .replace("], ", "\n").replaceAll(",|\\[|\\]", ""); 

System.out.println(s); 

此打印:

1 2 3 
4 5 6 
7 8 9 

這承認爲了清楚和簡明控制和速度。如果您的矩陣較大並且/或者您想完全控制每個元素的打印方式(例如右對齊),則可能需要執行其他操作。

0
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()); 

} 
0
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);