简体   繁体   English

找不到合适的构造函数(Java)

[英]No Suitable Constructor Found (Java)

I am trying to compile my program here, but I am running into a small error and the error is "no suitable constructor found for ComplexNumber(double)." 我正在尝试在这里编译程序,但是遇到一个小错误,错误是“找不到适合ComplexNumber(double)的构造函数”。 Here is my code so far. 到目前为止,这是我的代码。

public class ComplexNumber extends ImaginaryNumber
{
    private double realCoefficient;

    public ComplexNumber ( )
    {
        super ( );
        this.realCoefficient = 1;
    }

    public ComplexNumber (double r, double i)
    {
        super (i);
        this.realCoefficient = r;
    }

    public ComplexNumber add (ComplexNumber another)
    {
        return new ComplexNumber (this.realCoefficient + another.realCoefficient); //the error at complile occurs here, right at new.
    }//More Codes

I have had this problem once, and that was because I did not have a parameterized constructor. 我曾经遇到过这个问题,那是因为我没有参数化的构造函数。 However this time, I do have one. 但是这次,我确实有一个。 So I have no idea what is the problem this time. 所以我不知道这次是什么问题。

Here is my code for the ImaginaryNumber 这是我的ImaginaryNumber的代码

public class ImaginaryNumber implements ImaginaryInterface
{
//Declaring a variable.
protected double coefficient;

//Default constructor.
public ImaginaryNumber( )
{
    this.coefficient = 1;
}

//Parameterized constructor.
public ImaginaryNumber(double number)
{
    this.coefficient = number;
}

//Adding and returing an imaginary number.
public ImaginaryNumber add (ImaginaryNumber another)
{
    return new ImaginaryNumber(this.coefficient + another.coefficient);
}//More Codes

My ImaginaryNumber class works fine. 我的ImaginaryNumber类工作正常。

Java is looking for a constructor of just: Java正在寻找一个Just的构造函数:

public ComplexNumber(double d){
   //to-do
}

You will need to make a constructor that fits those arguments. 您将需要创建一个适合这些参数的构造函数。

In the add method, you are attempting to pass exactly one parameter to a constructor, but you only have constructors that take 0 or 2 parameters. add方法中,您试图将一个参数恰好传递给构造函数,但是只有具有0或2个参数的构造函数。

It looks like you need to add the imaginary parts of the ComplexNumber anyway, so place that imaginary part addition in as the second parameter to the constructor. 看来您仍然需要添加ComplexNumber的虚部,因此将虚部添加作为构造函数的第二个参数。

Using the coefficient protected variable from Imaginary : 使用Imaginarycoefficient保护变量:

return new ComplexNumber (this.realCoefficient + another.realCoefficient,
                          this.coefficient + another.coefficient);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM