不想在 draw() 方法上使用初始化给定的高度/重量,相反,我想使用主驱动程序



所以,我一直在试图弄清楚如何能够通过给定的高度和宽度来绘制矩形的形状,但我遇到了麻烦,因为不知怎么的,我无法绘制矩形,相反,我能够将值放在draw()方法中。

对于draw()方法应该做以下描述方法必须使用System.out.println()"绘制"矩形。简单的打印宽度星号高度行数

界面形状表示闭合几何形状。它有三种方法。

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();


}

}

输出应该如下所示:

Shape rectangle1 = new Rectangle(4, 5); 
rectangle1.draw();
****
****
****
****
****

使用属于Rectangle对象实例的heightwidth成员变量。在你的例子中,宽度将是4,高度将是5基于一个对象实例化:Shape rectangle1 = new Rectangle(4, 5);

你的绘制方法看起来像:

@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(" ");
}
}

最新更新