您将创建两个类,一个用于盒子,一个用于三角形。每个图形,方框和三角形,都会有一个偏移量,表明它们从屏幕边缘缩进了多远。每个图形也将有一个尺寸,尽管对于一个盒子和一个三角形来说尺寸会有所不同。基类 Figure 将具有所有图形共有的任何属性的实例变量,并将具有所有图形具有的操作的方法。例如,每个图形都有一个给定的偏移量,每个图形都应该能够绘制自己。但是,由于我们不知道如何绘制未知形状的图形,因此将 drawHere() 声明为抽象方法,将 Figure 声明为抽象类。然后类 Box 和 Triangle 将是 Figure 的派生类,它们将提供 drawHere() 的实现。
方法 drawHere 将简单地在屏幕上缩进等于偏移量的空格数,然后在屏幕上写一个星号。这只是为了让您可以进行一些测试。您不打算在任何应用程序中使用此版本的 drawHere。当您定义盒子和三角形的类时,您将覆盖 drawHere 的定义。
drawAt 方法有一个 int 类型的参数。drawAt 方法插入与此参数相等的空行数,然后通过调用 drawHere 绘制图形。当您覆盖 drawHere 时,drawAt 也会生成正确的图形。
我需要一棵这样打印出来的圣诞树:
*
* *
* *
* *
* *
* *
* *
* *
* *
* *
*********************
-----
| |
| |
-----
图类:
public abstract class Figure
{
private int offset;
public Figure()
{
offset = 0;
}
public Figure(int theOffset)
{
offset = theOffset;
}
public void setOffset(int newOffset)
{
offset = newOffset;
}
public int getOffset()
{
return offset;
}
public void drawAt(int lineNumber)
{
for (int count = 0; count < lineNumber; count++)
System.out.println();
drawHere();
}
public abstract void drawHere();
}
三角班:
public class Triangle extends Figure
{
private int base;
public Triangle()
{
base = 0;
}
public Triangle(int offset, int base)
{
offset = 0;
this.base = base;
}
public void reset(int newOffset, int newBase)
{
newOffset = 0;
newBase = 0;
}
public void drawHere()
{
for (int count = 0; count < base; count++)
System.out.print("");
System.out.println("*");
}
}
盒子类:
public class Box extends Figure
{
private int height;
private int width;
public Box()
{
height = 0;
width = 0;
}
public Box(int offset, int height, int width)
{
super(offset);
this.height = height;
this.width = width;
}
public void reset(int newOffset, int newHeight, int newWidth)
{
newOffset = 0;
newHeight = 0;
newWidth = 0;
}
public void drawHere()
{
for (int count = 0; count < width; count++)
System.out.print("");
System.out.println('-');
}
}
图形测试类:
public class GraphicsTest
{
public static void main(String[] args)
{
Triangle top = new Triangle (5, 21);
Box base = new Box(13, 4, 5);
top.drawAt(1);
base.drawAt(0);
}
}
它返回的代码是:
*
-
我的问题是我需要在代码中修复什么以便打印出圣诞树。我已经尝试改变 drawHere 方法中的 for 循环变量,但没有任何东西可以解决它。谢谢您的帮助!