Anonymous
Anonymous asked in 電腦與網際網路程式設計 · 1 decade ago

物件導向JAVA撰寫程式問題??

請自行加入複製建構式與overlap(), isSquare(), display()等成員函數。(命名為JavaHW3_3_XX.java)

[程式片段]

....

public static void main(String[] args) {

Rectangle a = new Rectangle(0,0,5,-5) ;

Rectangle b = new Rectangle(-1,1,3,-4) ;

Rectange c = new Rectangle(a) ; // copy constructor (deep copy)

c.display(“c=”) ; // 印出 c: (0,0)-(5, -5)

if (c.isSquare()) System.out.println(“c is a square”) ;

if (b.isSquare())System.out.println(“b is a square”) ;

Rectangle d = a.overlap(b) ; //產生a,b重疊部分所構成的長方形

d.display(“d=”); //印出 d: (0,0) - (3, -4)

d = b.overlap(a) ;

d.display(“d=”); //印出 d: (0,0) - (3, -4)

}

可以幫我解答嗎?謝謝

2 Answers

Rating
  • 1 decade ago
    Best Answer

    請參考我的做法。請注意,(x1, y1) 必須為矩形的左上角座標,而 (x2, y2) 必須為右下角座標,否則要更改相關的程式。

    public class Rectangle {

    int x1, y1, x2, y2;

    public Rectangle(int a, int b, int c, int d) {

    x1 = a; y1 = b;

    x2 = c; y2 = d;

    }

    public Rectangle(Rectangle r) {

    this(r.x1, r.y1, r.x2, r.y2);

    }

    public void display(String s) {

    System.out.println(s + "(" + x1 + "," + y1 +

    ")-(" + x2 + "," + y2 + ")");

    }

    public boolean isSquare() {

    return Math.abs(x1-x2) == Math.abs(y1-y2);

    }

    public Rectangle overlap(Rectangle r) {

    int a = (x1 > r.x1) ? x1 : r.x1;

    int b = (y1 > r.y1) ? r.y1 : y1;

    int c = (x2 > r.x2) ? r.x2 : x2;

    int d = (y2 > r.y2) ? y2 : r.y2;

    if (a > c || b < d) return null;

    return new Rectangle(a, b, c, d);

    }

    public static void main(String[] args) {

    Rectangle a = new Rectangle(0,0,5,-5);

    Rectangle b = new Rectangle(-1,1,3,-4);

    Rectangle c = new Rectangle(a); // copy constructor (deep copy)

    c.display("c: "); // LX c: (0,0)-(5, -5)

    if (c.isSquare()) System.out.println("c is a square");

    if (b.isSquare()) System.out.println("b is a square");

    Rectangle d = a.overlap(b); //a,b­|Һc

    d.display("d: "); //LX d: (0,0) - (3, -4)

    d = b.overlap(a);

    d.display("d: "); //LX d: (0,0) - (3, -4)

    }

    }

  • Ashley
    Lv 7
    1 decade ago

    你要不要把Rectangle的 class

    和建構式的程式碼放上來?

    不然不知道你傳變數過去會有什麼變化

Still have questions? Get your answers by asking now.