2009年5月25日 星期一

Lab: Static Method II

Define a Complex class with a static method for computing complex addition. Use (2+3i)*(4+5i) in your test.

class程式碼
------------------------------------------------<程式碼開始>--------------------------------------
public class ADTClass {
private int realNum = 0, imaginaryNum = 0;
public ADTClass(int realNum, int imaginaryNum) {
this.realNum = realNum;
this.imaginaryNum = imaginaryNum;
}
public ADTClass multiplication(ADTClass f) {
ADTClass ans = new ADTClass(1, 1);
ans.realNum = this.realNum * f.realNum - this.imaginaryNum * f.imaginaryNum;
ans.imaginaryNum = this.imaginaryNum * f.realNum + f.imaginaryNum * this.realNum;
return ans;
}
public String toString() {
return realNum + "+" + imaginaryNum + "i";
}
}
------------------------------------------------<程式碼結束>--------------------------------------

主程式碼
------------------------------------------------<程式碼開始>--------------------------------------
import java.util.*;
public class StaticMethodII {
    public static void main (String args[]) {
ADTClass f1, f2;
f1 = new ADTClass(2, 3);
f2 = new ADTClass(4, 5);
    System.out.println("f1 = " + f1.toString());
System.out.println("f2 = " + f2.toString());
System.out.println("f1 x f2 = " + f1.multiplication(f2).toString());
    }
}
------------------------------------------------<程式碼結束>--------------------------------------
附註:

沒有留言:

張貼留言