2010-07-24 142 views
1

我已經開始寫一個類來矩陣模型和編譯器給了我這個消息時「找不到符號」:測試Java代碼

Matrix.java:4: cannot find symbol 
symbol : constructor Matrix(int[][]) 
location: class Matrix 
    Matrix y = new Matrix(x);

這是我試圖編譯代碼:

public class Matrix<E> { 
    public static void main(String[] args) { 
     int[][] x = {{1, 2, 3}, {1, 2, 3}, {1, 2, 3}, {1, 2, 3}}; 
     Matrix y = new Matrix(x); 
     System.out.println(y.getRows()); 
     System.out.println(y.getColumns()); 
    } 
    private E[][] matrix; 
    public Matrix(E[][] matrix) {this.matrix = matrix;} 
    public E[][] getMatrix() {return matrix;} 
    public int getRows(){return matrix.length;} 
    public int getColumns(){return matrix[0].length;} 
} 

所以,我的問題是,爲什麼我得到這個錯誤,我應該改變什麼來解決這個問題?

回答

2

試試這樣說:

public class Matrix<E> { 
    public static void main(String[] args) { 
     Integer [][] x = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {0, 1, 0}}; 
     Matrix<Integer> y = new Matrix<Integer>(x); 
     System.out.println(y.getRows()); 
     System.out.println(y.getColumns()); 

     System.out.println("before: " + y); 
     Integer [][] values = y.getMatrix(); 
     values[0][0] = 10000; 
     System.out.println("after : " + y); 
    } 
    private E[][] matrix; 
    public Matrix(E[][] matrix) {this.matrix = matrix;} 
    public E[][] getMatrix() {return matrix;} 
    public int getRows(){return matrix.length;} 
    public int getColumns(){return matrix[0].length;} 
    public String toString() 
    { 
     StringBuilder builder = new StringBuilder(1024); 
     String newline = System.getProperty("line.separator"); 

     builder.append('['); 
     for (E [] row : matrix) 
     { 
      builder.append('{'); 
      for (E value : row) 
      { 
       builder.append(value).append(' '); 
      } 
      builder.append('}').append(newline); 
     } 
     builder.append(']'); 

     return builder.toString(); 
    } 
} 

編譯和運行我的機器上。

你需要考慮其他的東西:封裝和什麼時候「私人」不是私人的。查看對代碼的修改,看看我能夠修改你的「私有」矩陣。

+0

謝謝,編譯和運行在我的機器上。猜猜在我開始使用它之前,我應該多讀一些關於泛型的語法 – 2010-07-24 22:44:09

+1

爲什麼不接受答案? – duffymo 2010-07-24 22:46:03

+0

對於接受答案的速度,SO有時間限制。我嘗試了一下,但我必須等待一段時間才能接受(除非有人提出了一個超級驚人的答案,證明了神粒子的存在或類似的東西) – 2010-07-24 22:50:26

1

嘗試使用Integer[][]而不是int[][]。你的構造函數期望前者(因爲沒有原始類型參數),並且你傳遞後者。

+1

爲什麼這是upvoted?真正的問題是缺少類型聲明的通用部分。這個答案錯過了這個標記。 – 2010-07-24 22:48:47