Вопрос

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?

Это было полезно?

Решение

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

Другие советы

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);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top