In: Computer Science
The java.awt.Rectangle class of the standard Java library does
not supply a method
to compute the area or perimeter of a rectangle. Provide a subclass
BetterRectangle of the Rectangle class that has getPerimeter and
getArea methods. Do not add any instance variables. In the
constructor, call the setLocation and setSize methods of the
Rectangle class.
In Main class, provide 3 test cases that tests the methods that you supplied printing expected and actual results.
The test cases are: 1) One positive test case testing your method with valid inputs 2) Two negative test cases, testing your methods for invalid inputs and printing proper error message indicating proper error handling.
BetterRectangle.java
import java.awt.Rectangle;
public class BetterRectangle extends Rectangle {
//constructor
public BetterRectangle(int locx, int locy, int sizex,
int sizey) throws Exception{
//checking if size is less than
zero
if(sizex < 0 || sizey < 0)
{
throw new
Exception("Size less than zero\n\n");
}
//checking if both sizes are
zero
if(sizex == 0 && sizey ==
0) {
throw new
Exception("Size is zero\n\n");
}
//setting location ans size
this.setLocation(locx, locy);
this.setSize(sizex, sizey);
}
//calculating area
public double getArea() {
return this.getWidth() *
this.getHeight();
}
//calculating perimeter
public double getPerimeter() {
return 2 * (this.getWidth() +
this.getHeight());
}
}
Main.java
public class Main {
public static void main(String[] args) throws
Exception {
//valid test caes
BetterRectangle betRec1 = new
BetterRectangle(1,1,5,5);
System.out.println("Perimeter 1
Expected: 20 Actual: " + betRec1.getPerimeter());
System.out.println("Area 1
Expected: 25 Actual: " + betRec1.getArea() + "\n\n");
BetterRectangle betRec2 = new
BetterRectangle(1,1,1,1);
try {
//invalid test
case with size less than zero
betRec2 = new
BetterRectangle(1,1,-4,5);
}catch(Exception ex) {
System.out.println("Perimeter 2 Expected: 2 Actual: " +
betRec2.getPerimeter());
System.out.println("Area 2 Expected: -20 Actual: " +
betRec2.getArea());
System.out.println("Error 2:" + ex.getMessage());
}
BetterRectangle betRec3 = new
BetterRectangle(1,1,1,1);
try {
//invalid test
case with size equals 0
betRec3 = new
BetterRectangle(1,1,0,0);
}catch(Exception ex) {
System.out.println("Perimeter 3 Expected: 0 Actual: " +
betRec3.getPerimeter());
System.out.println("Area 3 Expected: 0 Actual: " +
betRec3.getArea());
System.out.println("Error 3:" + ex.getMessage());
}
}
}
Sample Output:
Perimeter 1 Expected: 20 Actual: 20.0
Area 1 Expected: 25 Actual: 25.0
Perimeter 2 Expected: 2 Actual: 4.0
Area 2 Expected: -20 Actual: 1.0
Error 2:Size less than zero
Perimeter 3 Expected: 0 Actual: 4.0
Area 3 Expected: 0 Actual: 1.0
Error 3:Size is zero