20145306实验二java面向对象程序设计
实验目的
设计实现复数类。
Complex复数类的方法有:构造函数、返回复数内容,以及复数间相加、减、乘运算。
加法:实部相加,虚部相加,最后以虚数的形式返回 减法:实部相减,虚部相减,最后以虚数的形式返回 乘法:实部相乘减去虚部相乘返回实部,实部虚部交错相乘后相加返回虚部,最后返回虚数形式 Complex类:
public class Complex {
protected int a;
protected int b;
public Complex(int a, int b) {
this.a = a;
this.b = b;
}
public String toString() {
return this.a + " + " + this.b + "i";
}
public static Complex addition(Complex complex1, Complex complex2) {
int a = complex1.a + complex2.a;
int b = complex1.b + complex2.b;
return new Complex(a, b);
}
public static Complex subtract(Complex complex1, Complex complex2) {
int a = complex1.a - complex2.a;
int b = complex1.b - complex2.b;
return new Complex(a, b);
}
public static Complex multiplication(Complex complex1, Complex complex2) {
int a = complex1.a * complex2.a - complex1.b * complex2.b;
int b = complex1.b * complex2.a + complex1.a * complex2.b;
return new Complex(a, b);
}
}
调用Complex类:
public class Main {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.println("输入个复数的实部和虚 部:");
int a = scanner.nextInt();
int b = scanner.nextInt();
System.out.println("输入个复数的实部和虚部:");
int c = scanner.nextInt();
int d = scanner.nextInt();
Complex fushu1=new Complex(a,b);
Complex fushu2=new Complex(c,d);
while(true) {
System.out.println("输入1.2.3.4.进行加减乘除运算");
int w = scanner.nextInt();
switch (w) {
case 1:
System.out.println(Complex.addition(fushu1, fushu2));
break;
case 2:
System.out.println(Complex.subtract(fushu1, fushu2));
break;
case 3:
System.out.println(Complex.multiplication(fushu1, fushu2));
break;
default:System.out.println("erorr");
}
}
}
}
测试代码
public class test {
public static void main(String[] args) {
Complex complex1 = new Complex(1, 2);
Complex complex2 = new Complex(3, 4);
if(Complex.addition(complex1, complex2).a!=4||Complex.addition(complex1, complex2).b!=6)
System.out.println("addition test failed ");
else
System.out.println("addition test passed");
if(Complex.subtract(complex1, complex2).a!=-2||Complex.subtract(complex1, complex2).b!=-2)
System.out.println("substract test failed");
else
System.out.println("substract test passed");
if(Complex.multiplication(complex1, complex2).a!=-5||Complex.multiplication(complex1, complex2).b!=10)
System.out.println("multiplication test failed");
else
System.out.println("multiplication test passed ");
}
}
单元测试
用Star UML 建模
PSP
步骤 | 耗时 | 百分比 |
需求分析 | 10 | 14% |
设计 | 15 | 21% |
代码实现 | 10 | 14% |
测试 | 20 | 28% |
分析总结 | 15 | 21% |