题目如下:
代码如下:
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));
}
}
运行结果如下:
其中自动生成的部分具体操作可参考: