Issue
So, I been trying to figured out how can I able draw the shape of a rectangle by given the height and the width on the main driver, but I was having trouble because somehow I couldn't able to draw the rectangle, instead I was able to put the values inside of the draw() methods.
For the draw() method was supposed to do this description: The draw method must “draw” the rectangle using System.out.println(). Simply print width number of asterisks in height number of lines.
The interface Shape represents a closed geometrical shape. It has three methods.
1. draw(): This has no parameters and returns void. The method draws the shape on the screen. 2. getArea(): The method has no parameters and returns the area of the shape. The return type is double. 3. getPerimeter(): The method has no parameters and returns the perimeter of the shape. The return type is double.
public class Rectangle implements Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
@Override
public void draw() {
/**
* Don't want to use the initialize given height/weight
* Instead use the main driver
*
*/
double height = 3,width = 3;
for(int i=0; i<height;i++) {
for(int w =0; w<width; w++) {
System.out.print("*");
}
System.out.println(" ");
}
}
@Override
public double getArea() {
return width*height;
}
@Override
public double getPerimeter() {
return 2*(height+width);
}
public boolean equals(Object obj)
{
// check that the type of the parameter is Rectangle
if( !(obj instanceof Rectangle) )
return false;
// we already know that obj is of type Rectangle, so it's safe to cast
Rectangle rectangleObject = (Rectangle) obj;
// return true or false depending on whether length and width have the same value
return height == rectangleObject.height && width == rectangleObject.width;
}
public String toString() {
String info = "Area: " + getArea() + "\n" + "Perimeter:" + getPerimeter();
return info;
}
public static void main(String[] args) {
Shape rectangle1 = new Rectangle(5,5);
rectangle1.draw();
}
}
The output should look like:
Shape rectangle1 = new Rectangle(4, 5);
rectangle1.draw();
****
****
****
****
****
Solution
Use the height
and width
member variables that are part of the Rectangle object instance. In your example, the width would be 4 and the height would be 5 based one the object instantiation via:
Shape rectangle1 = new Rectangle(4, 5);
Your draw method would look like:
@Override
public void draw() {
for(int i=0; i<this.height;i++) {
for(int w =0; w<this.width; w++) {
System.out.print("*");
}
System.out.println(" ");
}
}
Answered By - j_b