The missing code in task 1
were the methodsarea()
, perimeter()
and toString()
.
In task 2
I know that using built in collection such as Arraylist
would be efficient and simpler,So any new different idea and implementation are appreciated.
Make the classes Circle and Rectangle complete: write the missing code.
A static method
selectRectangle
accepts an array of areas of type Region, and returns an array that only contains the areas that are of type Rectangle. Create that method.Create an array that contains both circles (objects of type Circle) and rectangles (objects of type Rectangle). Write code that determines and shows the perimeter and area of these regions. Call the method selectRectangles with the created array as argument.
public interface Region {
double area();
double perimeter();
}
class Circle implements Region {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double area() {
return Math.PI * radius;
}
@Override
public double perimeter() {
return Math.PI * 2 * radius;
}
}
class Rectangle implements Region {
private double with;
private double length;
public Rectangle(double with, double length) {
this.length = length;
this.with = with;
}
@Override
public double area() {
return length * with;
}
@Override
public double perimeter() {
return 2 * (length + with);
}
public String toString() {
return "<" + this.with + this.with + this.area() + this.perimeter() + ">";
}
public static Rectangle[] selectRectangle(Region[] region) {
int countRect = 0;
for (int i = 0; i < region.length; i++) {
if (region[i] instanceof Rectangle) {
countRect++;
}
}
Rectangle[] rect = new Rectangle[countRect];
int companionVar = 0;
for (int i = 0; i < region.length; i++) {
if (region[i] instanceof Rectangle) {
rect[companionVar++] = (Rectangle) region[i];
}
}
return rect;
}
public static void main(String[] args) {
Region[] region = {new Circle(5),
new Rectangle(2, 4),
new Circle(2),
new Rectangle(7, 9),
new Circle(6)
};
for (int i = 0; i < region.length; i++) {
System.out.println(region[i].area() + region[i].perimeter());
}
Rectangle[] rectangle = selectRectangle(region);
}
}