To be able to do this, you should create a 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)
public 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 + ")";
}
}
public class Rectangle {
private Point topLeft;
private Point bottomRight;
public Rectangle(Point topLeft, Point bottomRight) {
this.topLeft = topLeft;
this.bottomRight = bottomRight;
}
public void display() {
int width = (int) (bottomRight.getX() - topLeft.getX());
int height = (int) (topLeft.getY() - bottomRight.getY());
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (j == 0 || j == width - 1 || i == 0 || i == height - 1) {
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());
}
public double area() {
return (bottomRight.getX() - topLeft.getX()) * (topLeft.getY() - bottomRight.getY());
}
public double perimeter() {
return 2 * ((bottomRight.getX() - topLeft.getX()) + (topLeft.getY() - bottomRight.getY()));
}
public Point centerPoint() {
return new Point((bottomRight.getX() - topLeft.getX()) / 2, (topLeft.getY() - bottomRight.getY()) / 2);
}
public boolean isSquare() {
return (bottomRight.getX() - topLeft.getX()) == (topLeft.getY() - bottomRight.getY());
}
}
Comments
Leave a comment