今晚的月色温柔

导航

java--设计复数类complex

【问题描述】根据下列类图和Main类中的main方法,设计复数类,其中add方法实现复数的加法运算、sub方法实现复数的减法运算。

鍥剧墖.png

【输入形式】1-7的整数
【输出形式】复数计算后的结果。针对不同实部和虚部,复数的输出格式为:0、2.0i、-2.0i、1.0+2.0i、1.0-2.0i
【样例输入】
【样例输出】
【样例说明】
【评分标准】


import  java.util.Scanner;
class Complex{

private double realPart;
private double imagPart;
public Complex(){}
public Complex(double real,double imag)
{this.imagPart=imag;
this.realPart=real;}
public void setRealPart(double real)
{this.realPart=real;}
public void setImagPart(double imag)
{this.imagPart=imag;}
public static Complex add(Complex c1,Complex c2)
{return new Complex(c1.realPart+c2.realPart,c1.imagPart+c2.imagPart);}
public Complex add(Complex c)
{this.realPart+=c.realPart;
this.imagPart+=c.imagPart;
return this;}
public static Complex sub(Complex c1,Complex c2)
{return new Complex(c1.realPart-c2.realPart,c1.imagPart-c2.imagPart);}
public Complex sub(Complex c)
{this.realPart-=c.realPart;
this.imagPart-=c.imagPart;
return this;}
public String toString(){
if(realPart==0&&imagPart==0)return "0";
if(imagPart==0) return realPart+"";
if(realPart==0) return imagPart+"i";
if(imagPart>0) return realPart+"+"+imagPart+"i";
return realPart+""+imagPart+"i";
}
}


public  class  Main  {
        public  static  void  main(String[]  args)  {
                Complex  c1=new  Complex();
                Complex  c2=new  Complex(0,1);
                int  selected;
                Scanner  in=new  Scanner(System.in);
                selected=in.nextInt();
                switch(selected){
                case  1:
                        System.out.println(c1);
                        break;
                case  2:
                        System.out.println(c2);
                        break;
                case  3:
                        c1.setRealPart(1);
                        c1.setImagPart(-1);
                        System.out.println(c1);
                        break;
                case  4:
                        c1.setRealPart(1);
                        System.out.println(c1.add(c2));        
                        break;
                case  5:
                        c1.setImagPart(-1);
                        System.out.println(c1.sub(c2));    
                        break;
                case  6:
                        System.out.println(Complex.add(c1,c2));    
                        break;
                case  7:
                        System.out.println(Complex.sub(c1,  c2));    
                        break;
                }
                in.close();
        }
}

posted on 2020-10-10 12:19  1022  阅读(1172)  评论(0编辑  收藏  举报