Question: Requirement: Using the Rectangle class you created in Chapter 11s programming assignment, create a second class called RectangleComparator that implements the Comparator interface to compares
Requirement:
Using the Rectangle class you created in Chapter 11s programming assignment, create a second class called RectangleComparator that implements the Comparator interface to compares two Rectangle objects according to area.
Create a third class called RectangleSortTest that contains the main method. The method should create a List containing five Rectangle objects, not in order by area. The method should print the list, displaying each rectangles area. Then sort the list, and print the list again showing the list has been sorted by area. This test class does not need to ask users for input, nor does it need to do any additional error checking.
My code:
public class Rectangle {
private double width; private double height;
public Rectangle(double width, double height) { setWidth(width); setHeight(height); }
public double getWidth() { return width; }
public double getHeight() { return height; }
public void setWidth(double width) { if(width < 0 || width > 20) { throw new IllegalArgumentException("Width is not in range"); } this.width = width; }
public void setHeight(double height) { if(height < 0 || height > 20) { throw new IllegalArgumentException("Height is not in range"); } this.height = height; }
public double calculatePerimeter() { return 2 * (width + height); }
public double calculateArea() { return width * height; } }
----------------------------------------------------
import java.util.Scanner;
public class RectangleTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try { System.out.println("Enter width and length: "); int x = sc.nextInt(); int y = sc.nextInt(); Rectangle rectangle = new Rectangle(x, y); System.out.println("Height: " + rectangle.getHeight()); System.out.println("Width: " + rectangle.getWidth()); System.out.println("Area: " + rectangle.calculateArea()); System.out.println("Perimeter: " + rectangle.calculatePerimeter()); }catch (Exception ex) { System.out.println(ex.getMessage()); }
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
