62,616
社区成员
发帖
与我相关
我的任务
分享
import java.util.Random;
public class Test
{
public static void main(String[] args)
{
int count = 5;
Location[] location = new Location[count];
for (int i = 0; i < count; i++)
{
location[i] = new Location(); //这里也要初始化
}
setLocation(location,450,600);
}
public static void setLocation(Location[] location,int rangex,int rangey)
{
Random random=new Random();
Loop:
for(int i=0;i<location.length;i++)
{
int tempx = random.nextInt(rangex);
int tempy = random.nextInt(rangey);
for(int j=0;j<i;j++)
{
if(!isIntersect(location[j].x,location[j].y,tempx,tempy))
{
i--;
continue Loop;
}
}
location[i].x = tempx;
location[i].y = tempy;
System.out.println("第"+i+"个的横坐标"+location[i].x+"\n");
System.out.println("第"+i+"个的纵坐标"+location[i].y+"\n");
}
}
//判断两个正方形有没有相交:两个左上角的横坐标距离大于100,且纵坐标距离大于100,否则相交
public static boolean isIntersect(int x1,int y1,int x2,int y2)
{
if(Math.abs(x1-x2)>100&&Math.abs(y1-y2)>100)
return true;
else
return false;
}
}
class Location
{
int x;
int y;
}