4. 编写 Complex 类表示数学上的复数概念,具体包括:① real 和 image 字段,分别表示复数的实部和虚部。② 读取和设置 real/ ima ge 字段的 get 和.....

题目如下:

代码如下:

package Complex;

public class Complex {
		//定义
		public int real;
		public int image;
		//读取与设置功能
		public int getReal() {
			return real;
		}
		public void setReal(int real) {
			this.real = real;
		}
		public int getImage() {
			return image;
		}
		public void setImage(int image) {
			this.image = image;
		}
		//构造方法
		public Complex(int real, int image) {
			super();
			this.real = real;
			this.image = image;
		}
		
		//输出
		public void printInfo() {
			System.out.println(real+"+"+image+"i");
		}
		//相加
		void add(Complex anotherComplex){
			Complex a=anotherComplex;
			a.real=this.real+anotherComplex.real;
			a.image=this.image+anotherComplex.image;
			a.printInfo();
			//return anotherComplex;
			
		}
		
		@Override
		public boolean equals(Object obj) {
			if (this == obj)
				return true;
			if (obj == null)
				return false;
			if (getClass() != obj.getClass())
				return false;
			Complex other = (Complex) obj;
			if (image != other.image)
				return false;
			if (real != other.real)
				return false;
			return true;
		}
}

 

package Complex;

public class ComplexTest {
	public static void main(String[] args) {
		
	Complex complex1 =new Complex(1, 2);
	Complex complex2 =new Complex(3, 5);
	Complex complex3 =new Complex(1, 2);
	Complex complex4 =new Complex(7, 8);
	complex1.printInfo();
	System.out.println("complex1 real= "+complex1.getReal());
	System.out.println("complex1 image= "+complex1.getImage());
	System.out.println();
	
	System.out.println("complex4原real: "+complex4.getReal());
	System.out.println("complex4原image:"+complex4.getImage());
	complex4.setReal(3);
	complex4.setImage(4);
	System.out.println();
	System.out.println("complex4改后real: "+complex4.getReal());
	System.out.println("complex4改后image: "+complex4.getImage());
	System.out.println();
	
	
	System.out.println("相加结果: ");complex1.add(complex2);
	System.out.println();
	
	System.out.println("两复数是否相等: "+complex1.equals(complex3));
	}
}

运行结果如下:

 

其中自动生成的部分具体操作可参考: 

 https://mp.csdn.net/mp_blog/creation/editor/134772445

  • 10
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值