我正在开展一个项目,我必须用随机起点和随机大小绘制20个圆圈。然后我必须确定是否有任何圆相交。如果圆与另一个圆相交,我必须将该圆圈着色为绿色。如果圆圈不与另一个圆相交,则颜色需要为红色。我有所有的代码......我想...但是当我运行它时,我仍然得到一些应该是绿色的圆圈,而不是红色。这是我的代码。任何帮助将不胜感激。
import java.awt.Graphics;
import javax.swing.JPanel;
import java.util.Random;
import javax.swing.JFrame;
import java.awt.*;
public class IntersectingCircles extends JPanel
{
private int[] xAxis = new int [20]; // array to hold x axis points
private int[] yAxis = new int [20]; // array to hold y axis points
private int[] radius = new int [20]; // array to hold radius length
public static void main (String[] args)
{
JFrame frame = new JFrame("Random Circles");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new IntersectingCircles());
frame.pack();
frame.setVisible(true);
}
public IntersectingCircles()
{
setPreferredSize(new Dimension(1300, 800)); // set window size
Random random = new Random();
for (int i = 0; i < 20; i++)
{
xAxis[i] = random.nextInt(800) + 100;
yAxis[i] = random.nextInt(500) + 100;
radius[i] = random.nextInt(75) + 10;
}
}
public void paintComponent(Graphics g)
{
for (int i = 0; i < 20; i++)
{
int color = 0;
for (int h = 0; h < 20; h++)
{
if(i < h)
{
double x1 = 0, x2 = 0, y1 = 0, y2 = 0, d = 0;
x1 = (xAxis[i] + radius[i]);
y1 = (yAxis[i] + radius[i]);
x2 = (xAxis[h] + radius[h]);
y2 = (yAxis[h] + radius[h]);
d = (Math.sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1)*(y2 - y1))));
if (d > radius[i] + radius[h] || d < (Math.abs(radius[i] - radius[h])))
{
color = 0;
}
else
{
color = 1;
break;
}
}
}
if (color == 0)
{
g.setColor(Color.RED);
g.drawOval(xAxis[i], yAxis[i], radius[i] * 2, radius[i] * 2);
}
else
{
g.setColor(Color.GREEN);
g.drawOval(xAxis[i], yAxis[i], radius[i] * 2, radius[i] * 2);
}
}
}
}
答案 0 :(得分:1)
在内部for
循环中,您只是将i
索引的圈子与带有h
索引的圈子进行比较,但仅将i < h
的圈子与for (int h = 0; h < 20; h++)
{
if(i < h)
{
...
进行比较,因为条件:
i
因此,您应该将每个h
圈与每个for (int h = 0; h < 20; h++)
{
if(i != h) //note the change here
{
...
圈进行比较,除非它们是相同的。你想要的是:
{{1}}