Encapsulation
Create a class main and class for a point (that has an x-coordinate and a y-coordinate). Also, create another class called Rectangle. The Rectangle should have 2 points, the top left and the bottom right. Implement the following methods for the Rectangle:
Input
A pair of numbers representing the points for the rectangle (x and y).
5 8
Output
The first few lines contain the drawn rectangle. After one empty line, the next line prints either "RECTANGLE" or "SQUARE".
#·#·#·#·#·#
#·········#
#·········#
#·········#
#·········#
#·········#
#·········#
#·········#
#·#·#·#·#·#
RECTANGLE
AREA:·40
PERIMETER:·26
CENTER·POINT:·(2.50,4.00)
import java.util.Scanner;
class Point {
private double x;
private double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
}
class Rectangle {
private Point topLeft;
private Point bottomRight;
public Rectangle(Point topLeft) {
this.topLeft = topLeft;
this.bottomRight = new Point(0, 0);
}
public void display() {
int width = (int) (bottomRight.getX() - topLeft.getX());
width = Math.abs(width);
int height = (int) (topLeft.getY() - bottomRight.getY());
height = Math.abs(height);
for (int i = 0; i <= height; i++) {
for (int j = 0; j <= width; j++) {
if (j == 0 || j == width || i == 0 || i == height) {
System.out.print("#");
} else {
System.out.print(".");
}
}
System.out.println();
}
System.out.println(isSquare() ? "\nSQUARE" : "\nRECTANGLE");
System.out.println("AREA: " + area());
System.out.println("PERIMETER: " + perimeter());
System.out.println("CENTER POINT: " + centerPoint());
}
private double area() {
return Math.abs((bottomRight.getX() - topLeft.getX())) * Math.abs((topLeft.getY() - bottomRight.getY()));
}
private double perimeter() {
return 2 * (Math.abs((bottomRight.getX() - topLeft.getX())) + Math.abs((topLeft.getY() - bottomRight.getY())));
}
private Point centerPoint() {
return new Point(Math.abs((bottomRight.getX() - topLeft.getX())) / 2,
Math.abs((topLeft.getY() - bottomRight.getY())) / 2);
}
private boolean isSquare() {
return Math.abs((bottomRight.getX() - topLeft.getX())) == Math.abs((topLeft.getY() - bottomRight.getY()));
}
}
public class App {
/**
* The start point of the program
*
* @param args
*
*/
public static void main(String[] args) {
Scanner keyBoard = new Scanner(System.in);
int x = keyBoard.nextInt();
int y = keyBoard.nextInt();
Rectangle rectangle = new Rectangle(new Point(x, y));
rectangle.display();
keyBoard.close();
}
}
Comments
Leave a comment