2009年5月11日 星期一

Lab Static Method

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



------------------------------------------------<程式碼開始>--------------------------------------
import java.util.*;
class ADTClass {
private int realNum = 0, imaginaryNum = 0;
public ADTClass(int realNum, int imaginaryNum) {
this.realNum = realNum;
this.imaginaryNum = imaginaryNum;
}
public static ADTClass add(ADTClass a, ADTClass b) {
ADTClass ans = new ADTClass(1, 1);
ans.realNum = a.realNum + b.realNum;
ans.imaginaryNum = a.imaginaryNum + b.imaginaryNum;
return ans;
}
public String toString() {
return realNum + "+" + imaginaryNum + "i";
}
}
public class LabStaticMethod {
    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 + f2 = " + ADTClass.add(f1, f2).toString());
    }
}
------------------------------------------------<程式碼結束>--------------------------------------
附註:

沒有留言:

張貼留言