Java 从同一类中的方法调用构造函数

Java 从同一类中的方法调用构造函数,java,Java,我是java新手,正在学习创建对象类。我的一项家庭作业要求我在同一对象类的方法中至少调用一次构造函数。我得到一个错误,该错误表示DoubleMatrix类型的DoubleMatrix(double[][])方法未定义 这是我的构造函数: public DoubleMatrix(double[][] tempArray) { // Declaration int flag = 0; int cnt; // Statement // check to se

我是java新手,正在学习创建对象类。我的一项家庭作业要求我在同一对象类的方法中至少调用一次构造函数。我得到一个错误,该错误表示DoubleMatrix类型的DoubleMatrix(double[][])方法未定义

这是我的构造函数:

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
public DoubleMatrix(双[][]临时数组)
{
//声明
int标志=0;
int-cnt;
//声明
//检查doubArray是否不为null,是否有超过0行
if(tempArray==null | | tempArray.length<0)
{
flag++;
}
//检查每行的长度是否相同
如果(标志==0)
{

对于(cnt=0;cnt您可以使用
this()
从调用构造函数(或
super()
调用父类构造函数),但您不能从另一个方法调用构造函数。可能您想创建一个新对象?如果是,请使用
new object()
。将为新对象调用构造函数。

不能从方法调用构造函数,只能使用此关键字或超级关键字从其他构造函数调用构造函数。只能调用一次构造函数,它必须是构造函数体中的第一条语句。如果不从构造函数调用任何构造函数body java编译器将在构造函数中隐式插入super()语句

有人能给我指出正确的方向并解释我出错的原因吗?

原因是..您没有正确声明对象。正如少数回答所指出的,您需要给出一个名为
new
的关键字。此
new
关键字为堆内存中的类
DoubleMatrix
创建一个新对象

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

希望这有助于

在其他部分添加新关键字…其他{newMatrix=newdouble[0][0];newdoublematrix(newMatrix)}@asvikki谢谢,这让错误消失了。你能解释一下为什么这样做吗?