본문 바로가기
공부

사각형의 좌표를 이용해 넓이 계산, 비교

by 하프상 2017. 3. 30.

public class Rectangle{


int x1, y1, x2, y2;

int res;

int cal1, cal2, cal3, cal4;

Rectangle()

{

x1 = 0;

y1 = 0;

x2 = 0;

y2 = 0;

}

Rectangle(int x1, int y1, int x2, int y2)

{

this.x1 = x1;

this.y1 = y1;

this.x2 = x2;

this.y2 = y2;

}

void set(int x1, int y1, int x2, int y2)

{

this.x1 = x1;

this.y1 = y1;

this.x2 = x2;

this.y2 = y2;

}

int square()

{

if(x1>x2 && y1>y2)

{

res = (x1-x2)*(y1-y2);

}

else if(x1>x2 && y1<y2)

{

res = (x1-x2)*(y2-y1);

}

else if(x1<x2 && y1>y2)

{

res = (x2-x1)*(y1-y2);

}

else if(x1<x2 && y1<y2)

{

res = (x2-x1)*(y2-y1);

}

else

{

return 0;

}

return res;

}

void show()

{

System.out.println("x1:"+x1 + " y1:"+y1 + " x2:"+x2+ " y2:"+y2);

System.out.println("사각형의 넓이는 : "+square());

}

boolean equals(Rectangle r)

{

cal1 = x1 - x2;

cal2 = y1 - y2;

int a = Math.abs(cal1);

int b = Math.abs(cal2);

int c = Math.abs(r.x1 - r.x2);

int d = Math.abs(r.y1 - r.y2);

if(a == c && b == d)

{

return true;

}

else return false;

}

public static void main(String[] args) {

// TODO Auto-generated method stub

Rectangle r = new Rectangle();

Rectangle s = new Rectangle(1, 1, 2, 3);

r.show();

s.show();

System.out.println(s.square());

r.set(1, 1, 2, 3);

r.show();

System.out.println(r.square());

if(r.equals(s))

{

System.out.println("두 사각형은 같습니다.");

}

else

{

System.out.println("두 사각형은 같지 않습니다.");

}


}


}



댓글