Ladywithahat Ladywithahat - 17 days ago 6
Java Question

How to write a toString() method that should return complex number in the form a+bi as a string?

The method should return the Complex numbers in String format. The toString() method should return Complex numbers in the form a+bi as a String,where a is the real part and b is the imaginary part

Answer

You can override toString() to get the desired description of the instances/classes.

Code:

class ComplexNum
{
    int a,b;

    ComplexNum(int a , int b)
    {
        this.a = a;
        this.b = b;
    }

    @Override
    public String toString()
    {
        return a + "+" + b + "i";
    }

    public static void main(String[] args)
    {
        ComplexNum c = new ComplexNum(10,12);
        System.out.println("Complex Number is: " + c);
    }
}

I hope it helped.

Comments