定義複數類Complex,實現以下功能:
(1)構造函數
(2)加減乘除函數
(3)toString()函數
(4)equals()函數
(5)編寫測試類,實現鍵盤讀取數據創建複數對象,並測試Complex類定義的函數
實現代碼:
package CurriculumDesign;
import java.util.Scanner;
/*
1.定義複數類Complex,實現以下功能:
(1)構造函數
(2)加減乘除函數
(3)toString()函數
(4)equals()函數
(5)編寫測試類,實現鍵盤讀取數據創建複數對象,並測試Complex類定義的函數
*/
public class Test1 {
public static void main(String[] args)
{
//初始化數組
double[] array = Complex.init();
//初始化複數對象
Complex complex1 = new Complex(array[0],array[1]);
Complex complex2 = new Complex(array[2],array[3]);
//加減乘除運算並輸出
System.out.println("加:"+complex1.add(complex2).toString());
System.out.println("減:"+complex1.subtract(complex2).toString());
System.out.println("乘:"+complex1.multiply(complex2).toString());
System.out.println("除:"+complex1.divide(complex2).toString());
//判斷是否相等並輸出
System.out.println("是否相等:" + complex1.equals(new Complex(1.0, 1.0)));
}
}
class Complex {
private double real = 0.0;
private double image = 0.0;
//無參構造
public Complex() {
}
//有參構造函數
Complex(double real, double image) {
this.real = real;
this.image = image;
}
//加
public Complex add(Complex complex)
{
return new Complex(this.real+complex.real,this.image+complex.image);
}
//減
public Complex subtract(Complex complex)
{
return new Complex(this.real-complex.real,this.image-complex.image);
}
//乘
//設z1=a+bi,z2=c+di(a、b、c、d∈R)是任意兩個複數,那麼它們的積(a+bi)(c+di)=(ac-bd)+(bc+ad)i
public Complex multiply(Complex complex)
{
return new Complex(this.real*complex.real-this.image*complex.image,this.image*complex.real+this.real*complex.image);
}
//除
//(a+bi)/(c+di)=(ac+bd)/(c^2+d^2) +((bc-ad)/(c^2+d^2))i
public Complex divide(Complex complex)
{
double real = (this.real*complex.real+this.image*complex.image)/(complex.real*complex.real+complex.image*complex.image);
double image = (this.image*complex.real-this.real*complex.image)/(complex.real*complex.real+complex.image*complex.image);
return new Complex(real,image);
}
//重寫toString()
public String toString()
{
//當虛部爲零時省略虛部,當虛部不爲零但實部爲零時省略實部
if (this.image == 0) { return this.real+""; }
else if (this.image > 0) {
if (this.real == 0) return this.image + "i";
else return this.real + "+" + this.image + "i";
}
else{
if (this.real == 0) return this.image+"i";
else return this.real+""+this.image+"i";
}
}
//是否相等
public boolean equals(Complex complex)
{
if ((this.real == complex.real) && (this.image == complex.image))
{
return true;
}
return false;
}
//從鍵盤輸入,並存放在數組中
public static double[] init()
{
Scanner scanner = new Scanner(System.in);
double[] array = new double[4];
System.out.println("請分別輸入第一個複數的實部、虛部,第二個複數的實部、虛部:");
for (int i = 0; i < 4; i++) array[i] = Double.parseDouble(scanner.next());
scanner.close();
return array;
}
}