Question

I need to make a toString() function that returns the string "3 + 2i" for a Complex object Complex(3,2).

This is what Iv done, but I am getting the below error, which I don't know what it means.

As of release 8, 'this' is allowed as a parameter name for the reciever type only, which has to be the first parameter.

public String toString()
{
    String s = ("%f + %fi",this.real,this.imaginary);

    return s;
}

Can anyone help me out on what I am doing wrong?

Était-ce utile?

La solution

Well, it is not Java. In order to format a String, you have to use String.format();

String s = String.format("%f + %fi", this.real, this.imaginary);

Autres conseils

You can return what ever String from toString() method. Only thing is you have to override toString() method. But the way you tried is wrong. you can return String value only from toString()

You can try this

 String s = String.format("%f + %fi",this.real,this.imaginary);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top