Complete the class Tiles which manages an ArrayList of Rectangles. Each rectangl
ID: 3864662 • Letter: C
Question
Complete the class Tiles which manages an ArrayList of Rectangles. Each rectangle represents a ceramic floor tile. Tiles contains a constructor and methods to process the rectangles
Provide a constructor that initializes the instance variable with an empty array list. Call the instance variable tiles.
Provide methods
add(Rectangle r) which adds a Rectangle object to the Tiles
totalArea() gets the sum of the areas of all the Rectangles in this Tiles
largest() gets the Rectangle with the largest area. If more than one Rectangle has the same ares, return the first.
toString() gets a string representation of the object. This is given to you
a private helper method area(Rectangle r) to get the area of a Rectangle. Use the helper method in the implementation of totalArea() and largest()
Provide Javadoc.
Use the following file:
TilesTester.java
Explanation / Answer
import java.util.ArrayList;
import java.util.List;
//Class Tiles and Rectangle is written inside the class TilesTester
public class Rectangle
{
public double height;
public double width;
public double length;
public double breadth;
public Rectangle(double height, double width, double length, double breadth)
{
this.height = height;
this.width = width;
this.length = length;
this.breadth = breadth;
}
}
public class Tiles
{
public ArrayList<Rectangle> rectangles;
public Tiles() //Constructor
{
this.rectangles = new ArrayList<Rectangle>();
}
public void add(Rectangle r) /*adding rectangle object to arraylist of rectangles*/
{
this.rectangles.add(r);
}
public double totalArea()
{
int i;
double totalArea = 0;
for(i = 0; i < rectangles.size(); i++)
{
rec= rectangles.get(i); //getting each object in the arraylist
totalArea +=area(rec); //adding the area of each rectangle
}
return totalArea;
}
double area(Rectangle r) //finds area of rectangle r
{
double area=0;
area=r.length*r.breadth*r.width*r.height;
return area;
}
public Rectangle largest()/* returns largest rectangle based on the area of each rectangle by comparing themselves
{
Rectangle largestRectangle= rectangles.get(0);
for(i = 1; i < rectangles.size(); i++){
if(area(rectangles.get(i)) > area(largestRectangle)) {
largestRectangle=rec;
}
}
return largestRectangle;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.