2013-10-27 40 views
4

我是新來的java和我正在學習創建對象類。我的一項家庭作業要求我在相同對象類的方法中至少調用一次構造函數。我收到說The method DoubleMatrix(double[][]) is undefined for the type DoubleMatrix從同一個類中的方法調用構造函數

這裏的錯誤是我的構造函數:

public DoubleMatrix(double[][] tempArray) 
{ 
    // Declaration 
    int flag = 0; 
    int cnt; 

    // Statement 

    // check to see if doubArray isn't null and has more than 0 rows 
    if(tempArray == null || tempArray.length < 0) 
    { 
     flag++; 
    } 

    // check to see if each row has the same length 
    if(flag == 0) 
    { 
     for(cnt = 0; cnt <= tempArray.length - 1 || flag != 1; cnt++) 
     { 
      if(tempArray[cnt + 1].length != tempArray[0].length) 
      { 
       flag++; 
      } 
     } 
    } 
    else if(flag == 1) 
    { 
     makeDoubMatrix(1, 1);// call makeDoubMatrix method 
    } 

}// end constructor 2 

這裏就是我嘗試調用構造函數的方法:

public double[][] addMatrix(double[][] tempDoub) 
{ 
    // Declaration 
    double[][] newMatrix; 
    int rCnt, cCnt; 

    //Statement 

    // checking to see if both are of same dimension 
    if(doubMatrix.length == tempDoub.length && 
      doubMatrix[0].length == tempDoub[0].length) 
    { 
     newMatrix = new double[doubMatrix.length][doubMatrix[0].length]; 

     // for loop to add matrix to a new one 
     for(rCnt = 0; rCnt <= doubMatrix.length; rCnt++) 
     { 
      for(cCnt = 0; cCnt <= doubMatrix.length; cCnt++) 
      { 
       newMatrix[rCnt][cCnt] = doubMatrix[rCnt][cCnt] + tempDoub[rCnt][cCnt]; 
      } 
     } 
    } 
    else 
    { 
     newMatrix = new double[0][0]; 
     DoubleMatrix(newMatrix) 
    } 

    return newMatrix; 
}// end addMatrix method 

能有人指出正確的方向並解釋爲什麼我得到一個錯誤?

+1

中的其他部分添加新的關鍵字...其他 { newMatrix =新的雙[0] [0]; 新的DoubleMatrix(newMatrix) } – Vikram

+0

@asvikki謝謝,這使錯誤消失。你能向我解釋爲什麼這項工作? – Nathan

+0

請參閱下面的答案 – Vikram

回答

5

有人能指點我正確的方向並解釋爲什麼我會出錯嗎?

原因是..你沒有正確地聲明你的對象。由於很少有答案指出,您需要提供一個名爲new的關鍵字。這個new關鍵字爲堆內存中的類DoubleMatrix創建一個新對象。

else { newMatrix = new double[0][0]; new DoubleMatrix(newMatrix) } 

希望這有助於

2

您可以使用this()inside another constructor(或super()調用父類構造函數)調用構造函數,但不能從其他方法構造函數。也許你打算創建一個新對象?如果是這樣,只需使用new Object();。該構造函數將被調用以獲取新對象。

3

您不能從方法調用構造函數,只能使用此關鍵字或超級關鍵字從其他構造函數調用構造函數。你只能調用一次構造函數,並且它必須是構造函數體中的第一個語句。如果你沒有從構造體中調用任何構造函數,java編譯器會隱式地將super()語句插入到構造函數中

相關問題