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

joyce33333 2012-02-01 08:04:51
我想在生成若干个坐标作为边长为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,很多东西还不是很清楚。请高手帮我看看,这个程序的问题出在哪里?谢谢!!!!!
...全文
122 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
CherryMs 2012-02-02
  • 打赏
  • 举报
回复
Location[] location = new Location[count];

这里只是初始化一个长度为5的数组 里面的元素都是null 还没有进行赋值
周靖峰 2012-02-01
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 ldh911 的回复:]

数组location,虽然初始化了数组空间,但没有初始化其元素。
使用前先加上这句话:
location[i] = new Location();
[/Quote]
楼上正解

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;
}
MiceRice 2012-02-01
  • 打赏
  • 举报
回复
数组location,虽然初始化了数组空间,但没有初始化其元素。
使用前先加上这句话:
location[i] = new Location();

62,616

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧