So I created a class of Rect which just has the properties of rectangle. How would I add an implementation so that the width and length must be integers greater than zero or if a given number is negative it will instead take absolute value. I have not used java in years and my experience with it is limited so any advice would help.
public class Rect {
int x;
int y;
int width;
int length;
public int getPerimeter() {
return (2 * width) + (2 * length);
}
public int getArea() {
return width * length;
}
public void move(int x, int y) {
this.x = x;
this.y = y;
}
public void changeSize(int n) {
this.width = n;
this.length = n;
}
public void print(int area, int perimeter) {
System.out.printf("X: %d\n", this.x);
System.out.printf("Y: %d\n", this.y);
System.out.printf("Length: %d\n", this.width);
System.out.printf("Width: %d\n", this.length);
System.out.printf("Area: %d\n", area);
System.out.printf("Perimeter: %d", perimeter);
}
public static void main(String[] args) {
Rect r1 = new Rect();
r1.length = 1;
r1.width = 2;
r1.x = 3;
r1.y = 4;
//test here
int area = r1.getArea();
int perimeter = r1.getPerimeter();
r1.print(area, perimeter);
}
}
I haven't really tried much as I am confused to where I should write the appropriate code.
To get the absolute values of negatives, you can replace this.width = width;
with this.width = Math.abs(width);
and the same for length and any other variables that cannot be negative.