Ladywithahat Ladywithahat - 1 year ago 119
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 Source

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


class ComplexNum
    int a,b;

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

    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.