2009年6月24日 星期三

LAB19 4/27 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




建立兩個private變數,re和im,分別代表實部(real)和虛部(imaginary)。
建立了
public void mutator(int r,int i)
{
re = r;
im = i;
}
使用兩個整數引數,可以對實虛部係數做修改。

建立了
public int re_access()
{
return re;
}
以及

public int im_access()
{
return im;
}

可分別回傳實部與虛部的係數,且型別為int。

最後是
public Complex add(Complex c)
{
int sum_re,sum_im;
sum_re = this.re + c.re;
sum_im = this.im + c.im;
Complex sum = new Complex(sum_re,sum_im);
return sum;
}

以class Complex 的物件為引數,回傳一個class Complex 的物件,該物件
為兩複數相加的總合。

其中在toString中
區分了im>0 im<0 和im = 0的狀況,以傳回正確的字串。

程式畫面 Demo

沒有留言:

張貼留言