Write a class called Rectangle that represents a rectangular two-dimensional reg
ID: 3875551 • Letter: W
Question
Write a class called Rectangle that represents a rectangular two-dimensional region. Your Rectangle objects should have the following methods public Rectangle(int x, int y, int width, int height) Constructs a new rectangle whose top-left corner is specified by the given coordinates and with the given width and height. Throw an IllegalArgumentException on a negative width or height. public int getHeight () Returns this rectangle's height. public int getwidth) Returns this rectangle's width. public int getX() Returns this rectangle's x-coordinate. public int getY() Returns this rectangle's y-coordinate. public String toString) Returns a string representation of this rectangle, such as "Rectangle [x-1 , y=2, width=3 , height-4 ] " .Explanation / Answer
Given below is the Rectangle class needed by the question.
Also to test that it works as intended, a sample test program is given in TestRectangle.java. Hope it helps.
Please do rate the answer if it was helpful. Thank you
To indent code in eclipse , select code by pressing ctrl+a and then indent using ctrl+i
Rectangle.java
==============
public class Rectangle {
private int x, y;
private int width, height;
public Rectangle(int x, int y, int width, int height)
{
this.x = x;
this.y = y;
if(width < 0)
throw new IllegalArgumentException("Width can not be negative");
if(height < 0)
throw new IllegalArgumentException("Height can not be negative");
this.width = width;
this.height = height;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public String toString()
{
return "Rectangle[x=" + x + ",y=" + y +",width=" + width +",height=" + height +"]";
}
}
TestRectangle.java
===========
public class TestRectangle {
public static void main(String[] args) {
System.out.println("Creating rectangle at 1,2 with width = 3 and height = 4");
Rectangle r1 = new Rectangle(1, 2, 3, 4);
System.out.println(r1);
System.out.println();
System.out.println("Creating rectangle at 1,2 with width = -3 and height = 5");
System.out.println("Should throw an exception ");
Rectangle r2 = new Rectangle(1, 2, -3, 5);
System.out.println(r2);
}
}
output
Creating rectangle at 1,2 with width = 3 and height = 4
Rectangle[x=1,y=2,width=3,height=4]
Creating rectangle at 1,2 with width = -3 and height = 5
Should throw an exception
Exception in thread "main" java.lang.IllegalArgumentException: Width can not be negative
at Rectangle.<init>(Rectangle.java:11)
at TestRectangle.main(TestRectangle.java:13)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.