ボックス用と三角形用の 2 つのクラスを作成します。ボックスと三角形の各図形には、画面の端からどれだけインデントされているかを示すオフセットがあります。各図形にもサイズがありますが、ボックスと三角形ではサイズが異なります。基本クラスの Figure には、すべての Figure が共通に持つプロパティのインスタンス変数と、すべての Figure が持つアクションのメソッドがあります。たとえば、すべての図には特定のオフセットがあり、すべての図はそれ自体を描画できる必要があります。ただし、形のわからない図形を描く方法がわからないので、 drawHere() を抽象メソッド、 Figure を抽象クラスとして宣言します。クラス Box と Triangle は Figure の派生クラスになり、drawHere() の実装を提供します。
メソッド drawHere は、画面上でオフセットに等しい数のスペースを単純にインデントし、画面にアスタリスクを書き込みます。これは、何かをテストできるようにするためです。このバージョンの drawHere をアプリケーションで使用する予定はありません。ボックスと三角形のクラスを定義するときに、drawHere の定義をオーバーライドします。
メソッド drawAt には、int 型のパラメーターが 1 つあります。メソッド drawAt は、このパラメーターに等しい数の空白行を挿入し、drawHere を呼び出して Figure を描画します。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('-');
}
}
GraphicsTest クラス:
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 ループである変数を変更しようとしましたが、何も修正されません。助けてくれてありがとう!