2012-03-29 55 views
1
5 import java.util.*; 
    6 
    7 class Matrix { 
    8  // declare the member field 
    9  private int[][] matrix; 
10 
12  public Matrix(int a, int b, int c, int d) { 
13   matrix = new int[2][2]; 
14   matrix[0][0] = a; 
15   matrix[0][1] = b; 
16   matrix[1][0] = c; 
17   matrix[1][1] = d; 
18  } 
19  // identity matrix 
20  public Matrix(char i) { 
21   matrix = new int[2][2]; 
22   matrix[0][0] = 1; 
23   matrix[0][1] = 0; 
24   matrix[1][0] = 1; 
25   matrix[1][1] = 0; 
26  } 
27 
29  public int[][] toPow(int n, int[][] matrix) { 
30   if (n == 1) 
31    return matrix; 
32   else { 
33    int[][] temp = matrix; 
34    for (int i = 0; i < 2; i++) { 
35     for (int j = 0; j < 2; j++) { 
36      temp[i][j] += matrix[i][j] * this.matrix[j][i]; 
37     } 
38    } 
39    return toPow(n - 1, temp); 
40   } 
41  } 
42  public int[][] toPow(int n) { 
43   return toPow(n, this.matrix); 
44  } 
45 } 
46 
47 class Maths { 
48 
49  public static void main(String[] args) { 
55   Matrix m = new Matrix(1,2,3,4); 
56   System.out.println(Arrays.toString(m.toPow(2))); 
57   System.out.println(Arrays.toString(new int[][] {{1,2},{3,4}})); 
58  } 
59 } 

Arrays.toString(陣列)應打印出數組的內容。但是當我試圖在代碼的最後2行中打印數組時,我得到的是地址而不是內容。任何人都可以請幫我理解爲什麼是這樣嗎?爲什麼會收到該數組的地址而不是值(二維數組)

回答

5

您看到在頂部陣列的每個元素上調用toString()的結果。但每個元素本身就是一個數組。使用Arrays.deepToString()代替:

System.out.println(Arrays.deepToString(m.toPow(2))); 
1

Arrays.toString()只適用於一維數組。嘗試遍歷數組的行並分別在每行上使用Arrays.toString()

0

Arrays.toString(INT [])支持陣列(一維),而不是矩陣(2 +尺寸)

0

可以調用Arrays.toString()的每個線矩陣或Arrays.deepToString()。

import java.util.Arrays; 

public class Test { 

    public static void main(String[] args) { 
     new Test().run(); 
    } 

    private void run() { 
     int[] v = { 1, 2, 3 }; 
     int[][] m = { { 1, 1, 1 }, { 2, 2, 2 }, { 3, 3, 3 } }; 
     System.out.println("Printing the array: "); 
     System.out.println(Arrays.toString(v)); 
     System.out.println("Printing the line addresses: "); 
     System.out.println(Arrays.toString(m)); 

     System.out.println("Priting the matrix: "); 
     for (int[] l : m) { 
      System.out.println(Arrays.toString(l)); 
     } 

     System.out.println("Priting the matrix (deepToString): "); 
     System.out.println(Arrays.deepToString(m)); 
    } 
} 

輸出:

Printing the array: 
[1, 2, 3] 
Printing the line addresses: 
[[[email protected], [[email protected], [[email protected]] 
Priting the matrix: 
[1, 1, 1] 
[2, 2, 2] 
[3, 3, 3] 
Priting the matrix (deepToString): 
[[1, 1, 1], [2, 2, 2], [3, 3, 3]] 
相關問題