第2个回答 2012-11-01
public class Complex {
// 属性;
private int i;
private int j;
// 默认构造方法(无参构造)
public Complex() {
i = 0;
j = 0;
}
public Complex(int i, int j) {
this.i = i;
this.j = j;
}
// get set 方法
public int getRealPart() {
return i;
}
public int getImaginaryPart() {
return j;
}
public void setRealPart(int i) {
this.i = i;
}
void setImaginaryPart(int j) {
this.j = j;
}
// 显示
public String showComp() {
if(getImaginaryPart()>0)
return getRealPart() + "+" + getImaginaryPart() + "i";
else
return getRealPart() +"-"+(- getImaginaryPart()) + "i";
}
// 加法
public static Complex addComp(Complex c1, Complex c2) {
return new Complex(c1.getRealPart() + c2.getRealPart(),
c1.getImaginaryPart() + c2.getImaginaryPart());
}
// 减法
public static Complex subComp(Complex c1, Complex c2) {
return new Complex(c1.getRealPart() - c2.getRealPart(),
c1.getImaginaryPart() - c2.getImaginaryPart());
}
// 乘法
public static Complex multiComp(Complex c1, Complex c2) {
return new Complex(
c1.getRealPart() * c2.getRealPart() + c1.getImaginaryPart()
* c2.getImaginaryPart(),
c1.getRealPart() * c2.getImaginaryPart() +c2.getRealPart()
* c1.getImaginaryPart());
}
// 比较
public static boolean equalComp(Complex c1, Complex c2) {
if (c1.getRealPart() == c2.getRealPart()
&& c1.getImaginaryPart() == c2.getImaginaryPart())
return true;
else
return false;
}
public static void main(String args[]){
Complex z1 = new Complex(1, 2);
Complex z2 = new Complex(1, -2);
Complex z4=addComp(z1, z2);
Complex z5=subComp(z1, z2);
Complex z6=multiComp(z1, z2);
// 显示5+8i和5-8i
System.out.println(z1.showComp());
System.out.println(z2.showComp());
boolean z7=equalComp(z1, z2);
System.out.println(z4.showComp());
System.out.println(z5.showComp());
System.out.println(z6.showComp());
if(z7)System.out.println("z1和z2相等!");
else System.out.println("z1和z2不相等!");
}
}
小弟初学Java 不足之处,多多指教!