2009年4月27日 星期一

Lab ADT

Define a Complex class and write an object oriented program to compute (2+3i)+(4+5i) in Java.
The methods should include an access and a mutator.

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

沒有留言:

張貼留言