Problem:
a. Create a class Rectangle. The class has attributes length and width, each of which defaults to 1. It has methods that calculate the perimeter and the area of the rectangle. It has set and get methods for both length and width. The set methods should verify that length and width are each floating-point numbers larger than 0.0 and less than 20.0.
b. Create a more sophisticated Rectangle class than the one you created in (a). This class stores only the Cartesian coordinates of the four corners of the rectangle. The constructor calls a set method that accepts four sets of coordinates and verifies that each of these is in the first quadrant with no single x- or y-coordinate larger than 20.0. The set method also verifies that the supplied coordinates do, in fact, specify a rectangle. Provide methods to calculate the length,width, perimeter and area. The length is the larger of the two dimensions. Include a predicate method isSquare which determines if the rectangle is a square.
b. Create a more sophisticated Rectangle class than the one you created in (a). This class stores only the Cartesian coordinates of the four corners of the rectangle. The constructor calls a set method that accepts four sets of coordinates and verifies that each of these is in the first quadrant with no single x- or y-coordinate larger than 20.0. The set method also verifies that the supplied coordinates do, in fact, specify a rectangle. Provide methods to calculate the length,width, perimeter and area. The length is the larger of the two dimensions. Include a predicate method isSquare which determines if the rectangle is a square.
Output:
Not needed.
Solution:
public class Rectangle { private int width = 0, length = 0; public Rectangle(int width, int length) { setWidth(width); setLength(length); } void setWidth(int width) { this.width = width; } void setLength(int length) { this.length = length; } int getWidth() { return this.width; } int getLength() { return this.length; } int getPerimeter() { return 2*getWidth() + 2*getLength(); } int getArea() { return getWidth()*getLength(); } boolean isSquare() { return (getWidth() == getLength()); } public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("Enter width:"); System.out.print("Enter length:"); int width=scan.nextInt(); int length=scan.nextInt(); Rectangle rect = new Rectangle(width, length); System.out.println("Area: " + rect.getArea()); System.out.println("Perimeter: " + rect.getPerimeter()); if(rect.isSquare()) { System.out.println("This is a square."); } else { System.out.println("This is not a square."); } } }
No comments :
Post a Comment