Java

[Java] 명품 자바프로그래밍 제 4장 실습문제 2번

graygreat 2017. 4. 11. 01:43
728x90
반응형


다음과 같은 멤버를 가지는 직사각형을 표현하는 Rectangle 클래스를 작성하라.


● int 타입의 x1, y1, x2, y2 필드 : 사각형을 구성하는 두 점의 좌표

● 생성자 2개 : 디폴트 생성자와 x1, y1, x2, y2의 값을 설정하는 생성자

● void set(int x1, int y1, int x2, int y2) : x1, y1, x2, y2 좌표 설정

● int square() : 사각형 넓이 리턴

● void show() : 좌표와 넓이 등 직사각형 정보의 화면 출력

● boolean equals(Rectangle r) : 인자로 전달된 객체 r과 현 객체가 동일한 직사각형이면 true 리턴


 Rectangle을 이용한 main() 메소드는 다음과 같으며 이 main() 메소드가 잘 작동하도록 하라.


public class Rectangle { private int x1, y1, x2, y2; // x1, y1, x2, y2의 값을 설정하는 생성자 Rectangle(int x1, int y1, int x2, int y2) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } // 기본 생성자 Rectangle() { this(0, 0, 0, 0); } // 좌표 설정 메소드 void set(int x1, int y1, int x2, int y2) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } // 사각형 넓이 리턴 메소드 int square() { return Math.abs((x1 - x2) * (y1 - y2)); } // 사각형 정보 출력 메소드 void show() { System.out.printf("x1 : %d, y1 : %d, x2 : %d, y2 : %d \n", x1, y1, x2, y2); System.out.println("넓이 : " + square()); } // 동일한 사각형인지 리턴하는 메소드 boolean equals(Rectangle r) { if (Math.abs(this.x1 - this.x2) == Math.abs(r.x1 - r.x2) && Math.abs(this.y1 - this.y2) == Math.abs(r.y1 - r.y2)) return true; return false; } public static void main(String[] args) { Rectangle r = new Rectangle(); // 인자가 없는 객체 생성 Rectangle s = new Rectangle(1, 1, 2, 3); // 인자가 있는 객체 생성 r.show(); s.show(); System.out.println(s.square()); r.set(-2, 2, -1, 4); r.show(); System.out.println(r.square()); if (r.equals(s)) System.out.println("두 사각형은 같습니다."); } }



수업시간에 실습 테스트로 했던 문제라 가볍게..

반응형