Pregunta

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?

¿Fue útil?

Solución

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);

Otros consejos

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);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top