วันอังคารที่ 20 สิงหาคม พ.ศ. 2556

class Fraction.

class Fraction { //สร้างClass ขึ้นมาเพื่อเก็บData & Method ทำให้สะดวกในการใช้งานต่อไปในภายหลัง
  int n; //ประกาศ Attribute n ขึ้นมาเป็นจำนวนเต็ม ซึ่งเป็นตัวแปรแบบ Local Variable
  int d;
  Fraction (int a, int b) { //Constructor ใช้ในการกำหนด Object
    n = a; 
    d = b;
  }
  void add (int z) { //Method เกี่ยวกับการบวกเศษส่วน Overloading
    this.n = this.d*z+this.n;
  }
  String toString() {
    String s = this.n+"/"+this.d;
    return s;
  }
  void reciprocal() { //Method เกี่ยวกับการสลับเศษและส่วน
    int tmp;
    tmp = n;
    n = d;
    d = tmp;
  }
}
  void setup() {
    Fraction f = new Fraction (2, 7);
    f.add (3); //ใส่ค่า บวก 3
    println (f.toString());
  }

out put
23/7

ไม่มีความคิดเห็น:

แสดงความคิดเห็น