请高手帮我看看这个生成随机两两不重叠的正方形的程序

joyce33333 joyce33333 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
我想在生成若干个坐标作为边长为100的正方形的左上角坐标,可以随机分布,并且这些矩形两两互不重叠。代码如下:

import java.util.Random;

public class Test {

public static void main(String[] args){
int count = 5;
Location[] location = new Location[count];
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;
}

运行时抛出nullpointerexception,显示位于location[i].x = tempx;
我刚学java,很多东西还不是很清楚。请高手帮我看看,这个程序的问题出在哪里?谢谢!!!!!
...全文

相关推荐

评论 3
收藏 已收藏
分享
返回顶部
joyce33333
Java SE 62,621 成员 307,251 内容