解答は
- ホスト名: earth.mlab.im.dendai.ac.jp
- ディレクトリ: /home/submit/JavaBeginners/[今日の日付]/[学籍番号]
に提出しなさい。ソースファイル (〜.java) のみを提出。 gFTP 等を使い ftp を用いて提出しなさい。
次のプログラムはクラスを用いない、 ボールが1秒ごとに移動するプログラムである。 このプログラムをボールをクラスとしたプログラムに書き換えなさい。
class MovingBall1 {
public static void main(String[] args) {
// (0,0) の位置から x 方向に 1 、y 方向に 2 ずつ動くボールの情報
int x = 0;
int y = 0;
int vx = 1;
int vy = 2;
print(x, y);
// 移動を 10 回繰り返す
for(int i = 0; i < 10; i++) {
x = x + vx;
y = y + vy;
print(x, y);
}
}
static void print(int x, int y) {
System.out.println("ボールの位置は (" + x + "," + y + ")");
}
}
ボール (Ball) クラスを用いたプログラムの大枠は次のとおり。 ファイル名は MovingBall2.java とする。
class MovingBall2 {
public static void main(String[] args) {
Ball ball = new Ball();
// ボールの位置(0,0)、移動量(1,2)を設定
ball.setXY(0,0);
ball.setVXVY(1,2);
for(int i = 0; i < 10; i++) {
ボールを移動させ、
ボールの現在値 (座標) を表示する処理をここに書く;
}
}
}
class Ball {
属性の宣言;
void setXY .... {
x座標とy座標を設定する処理をここに書く;
}
void setVXVY .... {
x方向の移動量 vx と、y方向の移動量 xy を設定する処理をここに書く;
}
void move .... {
ボールを 1 回ぶん移動する処理をここに書く;
}
void print .... {
ボールの座標情報を表示する処理をここに書く;
}
}
面積を求めることができる三角形を表わすクラス (Triangle) を作成しなさい。 このクラス Triangle を用いて底辺と高さを与えて面積を求めるプログラムを作成しなさい。
mainメソッドを作成するクラスは TrianglesArea とする。 (ファイル名 TrianglesArea.java)
class TrianglesArea {
public static void main(String[] args) {
Triangle t = new Triangle();
tの底辺と高さを設定
t面積の求め表示
}
}
// 三角形を表わすクラス
class Triangle {
属性の宣言;
メソッドの宣言1
メソッドの宣言2
....
}