電子書籍の厳選無料作品が豊富!

結城浩さんの本に載っていたプログラムです。

ですが、説明がわかりにくくていまいち処理がわからなかったので
質問させていただきました。

どうやら、X軸とY軸がありY軸は下に行けばいくほど数字が大きくなる。
X軸は右に行けばいくほど大きくなる。座標上にある、二つの長方形の重なりあう部分の座標を求めるプログラムのようです。(イメージとしては、下に添付してある画像のような感じになるようです。)

質問としては一つです。
プログラム中のこの部分なのですが、おそらく「長方形の座標を示している」行であると思います。

a = new Rectangle(0, 0, 20, 10);
b = new Rectangle(5, 5, 20, 10);
c = new Rectangle(20, 10, 20, 10);
d = new Rectangle(-10, -20, 100, 200);
e = new Rectangle(21, 11, 20, 10);

その後の処理としては、aとb→c→d→eというようにそれぞれ比較していっているのもなんとなくわかります。

ですが、しっかり解説されていなかったので、この4つの数字がどのように座標を示しているのかよくわかりませんでした。

よろしくお願いします。

class Rectangle {
final int INITIAL_WIDTH = 10;
final int INITIAL_HEIGHT = 20;
int width;
int height;
int x;
int y;
Rectangle() {
width = INITIAL_WIDTH;
height = INITIAL_HEIGHT;
x = 0;
y = 0;
}
Rectangle(int width, int height) {
this.width = width;
this.height = height;
this.x = 0;
this.y = 0;
}
Rectangle(int x, int y, int width, int height) {
this.width = width;
this.height = height;
this.x = x;
this.y = y;
}
void setLocation(int x, int y) {
this.x = x;
this.y = y;
}
void setSize(int width, int height) {
this.width = width;
this.height = height;
}
public String toString() {
return "[" + x + ", " + y + ", " + width + ", " + height + "]";
}
Rectangle intersect(Rectangle r) {
int sx = Math.max(this.x, r.x);
int sy = Math.max(this.y, r.y);
int ex = Math.min(this.x + this.width, r.x + r.width);
int ey = Math.min(this.y + this.height, r.y + r.height);
int newwidth = ex - sx;
int newheight = ey - sy;
if (newwidth > 0 && newheight > 0) {
return new Rectangle(sx, sy, newwidth, newheight);
} else {
return null;
}
}
public static void main(String[] args) {
Rectangle a, b, c, d, e;
a = new Rectangle(0, 0, 20, 10);
b = new Rectangle(5, 5, 20, 10);
c = new Rectangle(20, 10, 20, 10);
d = new Rectangle(-10, -20, 100, 200);
e = new Rectangle(21, 11, 20, 10);
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
System.out.println("e = " + e);
System.out.println("a と a の重なり = " + a.intersect(a));
System.out.println("a と b の重なり = " + a.intersect(b));
System.out.println("a と c の重なり = " + a.intersect(c));
System.out.println("a と d の重なり = " + a.intersect(d));
System.out.println("a と e の重なり = " + a.intersect(e));
}
}

「Javaの基礎のプログラム」の質問画像

A 回答 (1件)

a = new Rectangle(0, 0, 20, 10);


は座標(0,0)を基点とした幅20高さ10の長方形。
b = new Rectangle(5, 5, 20, 10);
は座標(5,5)を基点とした幅20高さ10の長方形。

てことよ。
メソッドintersectは
自分自身と、引数に渡された長方形の
重なり合っている部分の長方形の
基点と幅・高さを算出しているわ。

そしてtoStringで基点の座標と幅・高さを出力している。
    • good
    • 0
この回答へのお礼

回答ありがとうございます!!
なるほど、そういう仕組みになっているんですね。
解決することができました^^

お礼日時:2010/03/09 19:29

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!