2016-11-15 63 views
-5

該方法應返回複數的字符串表示形式。的toString()方法應在形式+雙返回複雜的數字作爲一個字符串,其中a是實數部分,b是虛部如何編寫一個toString()方法,該方法應該以字符串形式返回a + bi形式的複數?

public class Complex { 
     private double real; 
     private double imaginary; 

     //1.Complex() : This is the default constructor. 
     public void Complex(){ 
      this.real = 0; 
      this.imaginary = 0; 
     } 

     //2.Complex(double,double) 
     public void Complex(double r, double i){ 
      this.real = r; 
      this.imaginary = i; 
     } 

     //3.double getReal() 
     public double getReal(){ 
      return this.real; 
     } 

     //4.void setReal(double) 
     public void setReal(double real){ 
      this.real = real; 
     } 

     //5.double getImginary() 
     public double getImaginary(){ 
      return this.imaginary ; 
     } 

     //6. void setImaginary(double) 
     public void setImaginary(double imaginary){ 
      this.imaginary = imaginary; 
     } 

     //7.String toString() 
     public String toString1() { 
      return this.real + " + " + this.imaginary + "i"; 
     } 

     //8.Complex add(Complex) 
     public Complex add(Complex n){ 
      double r=this.real+n.real; 
      double i=this.imaginary + n.imaginary; 
      Complex s= new Complex(r,i); 
      return s; 

     } 

     //9.Complex sub(Complex) 
     public Complex sub(Complex n){ 
      double r= this.real- n.real; 
      double i= this.imaginary - n.imaginary; 
      Complex s= new Complex(r,i); 
      return s; 
     } 

     //10.Complex mul(Complex) 
     public Complex mul(Complex n){ 
      double r= this.real*n.real - this.imaginary*n.imaginary; 
      double i= this.real*n.imaginary+this.imaginary*n.real; 
      Complex s=new Complex(r,i); 
      return s; 
     } 


     //11.Complex div(Complex) 
     public Complex div(Complex n){ 
      double r= this.real/n.real- this.imaginary/n.imaginary; 
      double i = this.real/n.imaginary+this.imaginary/n.real; 
      Complex s=new Complex(r,i); 
      return s; 

} }

+0

這個班怎麼樣? –

+0

向我們展示您正在使用的基本類結構,比如字段是什麼,您如何獲得輸入'a'和'b'。 – SkrewEverything

+0

如何在'toString()'方法之外將它構建爲一個字符串?那麼,就在'toString()'方法內部做同樣的事情。 –

回答

0

您可以覆蓋toString()到獲取所需的實例/類的描述。

代碼:

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

我希望它幫助。

相關問題