Q: To write an Object-Oriented application that creates a Java class with severa
ID: 3713857 • Letter: Q
Question
Q: To write an Object-Oriented application that creates a Java class with several instance variables, a constructor to initialize the instance variables, several methods to access and update the instance variables’ values, along with other methods to perform calculations. In addition, Java Exception Handling is used to handle exceptions within the application. Also, write a test class that instantiates the first class and tests the class’s constructor and methods.
Details:
Rewrite the Rectangle class you wrote for Chapter 8 programming assignment to throw an IllegalArgumentException indicating there is a problem with the input parameters in the constructor and the set methods.
Also, rewrite the RectangleTest class from Chapter 8 to handle the exceptions thrown by the Rectangle class. Thoroughly tests the Rectangle class’s methods. This test class does not need to ask users for input. Just create the needed Rectangle objects to ensure that you test the Rectangle class’s methods well. The thoroughness of your testing in will impact your grade.
------------------------------------------------------
public class Rectangle {
private double width;
private double height;
public Rectangle(double width, double height) {
setWidth(width);
setHeight(height);
}
//Set and validate width and 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;
}
//get width value
public double getWidth() {
return width;
}
//get height value
public double getHeight() {
return height;
}
//calculate perimeter
public double calculatePerimeter() {
return 2 * (width + height);
}
//calculate area
public double calculateArea() {
return width * height;
}
}
-----------------------------------------------------------
public class RectangleTest {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5, 7);
System.out.println("Height: " + rectangle.getHeight());
System.out.println("Width: " + rectangle.getWidth());
System.out.println("Area: " + rectangle.calculateArea());
System.out.println("Perimeter: " + rectangle.calculatePerimeter());
}
}
Explanation / Answer
Hi Dear,
Please find my implementation.
YOur Rectangle is good.
I have modified Test Program.
Output:
Enter width and length:
-4
5
Width is not in range
Process finished with exit code 0
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.