3 つの配列 (x、y、および半径のサイズ) を使用して、ランダムな x 座標と y 座標と半径を持つ 5 つの円を作成しました。ただし、別の円と重なるかどうかに基づいて、円の色を動的に変更する必要があります。したがって、5 つの円のうちの 1 つがまったく重なっていない場合、その円は黒色になります。重なり合う円はシアンにする必要があります。中心点間の距離が半径の合計より小さい場合、2 つの円は重なっていると見なされます。
これは、これまでサークルクラスについて書いてきたものです。次のコードは、アプレット ウィンドウに 5 つの円を正常に描画し、距離は正常に計算されますが、問題は色付けにあります。色の塗りつぶしに論理エラーがあるようですが、ここには問題がありません。助言がありますか?どうもありがとう。
public class Circles extends Applet {
public void paint(Graphics page)
{
Random locator = new Random();
int [] xpt = new int [5];
int [] ypt = new int [5];
int [] rad = new int [5];
setPreferredSize (new Dimension(300, 300));
for (int i = 0; i < xpt.length; i++){
xpt[i] = locator.nextInt(100); //need to set a number or it goes into millions, cannot set it in Random()
ypt[i] = locator.nextInt(100);
rad[i] = locator.nextInt(100);
System.out.println("The #" + i + " x-point: " + xpt[i] + " y-point: " + ypt[i] + " radius: " + rad[i]); //for debugging purposes
for (int j = 0; j < xpt.length; j++){
double xpoint1 = xpt[i]+rad[i];
double ypoint1 = ypt[i]+rad[i];
double xpoint2 = xpt[j]+rad[j];
double ypoint2 = ypt[j]+rad[j];
double radius1 = rad[i];
double radius2 = rad[j];
double theDistance = distance(xpoint1,ypoint1,xpoint2,ypoint2);
System.out.println("Comparing " + i + " to " + j); //for debugging and logic checking
if (i==j)
;
else if (theDistance <= (radius1+radius2))
{
page.setColor(Color.cyan);
page.fillOval(xpt[i], ypt[i], rad[i], rad[i]);
//page.fillOval(xpt[j], ypt[j], rad[j], rad[j]);
System.out.println("Overlap occurred. Colored " + i + " and " + j + " cyan.");
System.out.println("Center points: ("+ xpoint1 +", "+ ypoint1 +") and ("+ xpoint2 + ", "+ ypoint2 + ").");
}
else
{
page.setColor(Color.black);
page.fillOval(xpt[i], ypt[i], rad[i], rad[i]);
//page.fillOval(xpt[j], ypt[j], rad[j], rad[j]);
System.out.println("No overlap. Made " + i + " and " + j + " black.");
}
}
}
}
public static double distance(
double x1, double y1, double x2, double y2) {
return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
}
}