[英]having trouble with loops in java
我正在播种程序生成的地图,但是当我运行它时,它应该在背景中工作,而应该显示带有不同颜色正方形的地图。 我需要帮助的方法在地图上选择了几个随机位置,并指定了一个随机类型作为起点。
这是整个方法
public void seed(){//seeds the map
double seedNum = (mapWidth*mapHeight*.02);//determine number of seed positions needed
if((int)seedNum < 1){//will always seed at least 1 square
seedNum = 1;
}
int seedListX[]= new int[(int)seedNum];//list of seeded coordinates to check for dupilcates
int seedListY[]= new int[(int)seedNum];
int seedX = (int)Math.random()*mapWidth;
int seedY = (int)Math.random()*mapHeight;
seedListX[0] = seedX;
seedListY[0] = seedY;
for(int i =1; i < (int)seedNum; i++){
int error = 0;
seedX = (int)Math.random()*mapWidth;
seedY = (int)Math.random()*mapHeight;
seedListX[i] = seedX;
seedListY[i] = seedY;
for(int j = 0; j < seedNum;j++){//goes through seed coordinates list to check for duplicates
if(seedX == seedListX[j] || seedY == seedListY[j]){
error = 1;
}
}
int type = (int)Math.random()*5+1;//choose random type
if(error != 1){
this.setType(seedX,seedY,type);
}else{
i--;
}//end inner loop
}
}//end outer loop
我测试了代码,删除了该块后,它工作正常
for(int j = 0; j < seedNum;j++){//goes through seed coordinates list to check for duplicates
if(seedX == seedListX[j] || seedY == seedListY[j]){
error = 1;
}
}
int type = (int)Math.random()*5+1;//this line is fine
if(error != 1){
this.setType(seedX,seedY,type);
}else{
i--;
}//end inner loop
我确定它是一个无限循环,但我没有看到它,感谢所有帮助。
每次都在发生
else{
i--;
}
因此for
循环永远不会递增并完成
也许当您这样做(每次都会发生,因此请检查i != j
)
error = 1;
你想打破
for(int j = 0; j < seedNum;j++){//goes through seed coordinates list to check for duplicates
if(seedX == seedListX[j] || seedY == seedListY[j]){
error = 1;
}
}
对于i == j
,条件将始终为true
(因为seedX == seedListX[i]
和seedY == seedListY[i]
)-您正在与自己发生冲突...
另外,您实际上不应该检查与尚未填充的种子坐标的碰撞。
假设seedNum = 2
。 第一次迭代将创建第一个种子:
i: 0
seedListX: [12, #JUNK#]
seedListY: [34, #JUNK#]
seedX: 12
seedY: 34
现在,在内循环的第一次迭代中:
j: 0
seedListX[j] == seedListX[0] == 12 == seedX
seedListY[j] == seedListY[0] == 34 == seedY
问题很明显-您正在将第一个坐标与第一个坐标进行比较-当然它们会发生碰撞!
但是 -还有另一个问题。 让我们看一下内部循环的第二次迭代:
j: 1
seedListX[j] == seedListX[1] == #JUNK#
seedListY[j] == seedListY[1] == #JUNK#
#JUNK#
恰好是0
,因为这是Java初始化事物的方式,但它仍然是垃圾-它包含一个任意(尽管行列式)值, 而不是第二个种子的实际坐标(尚未创建!)
您只应检查与先前迭代中创建的种子的碰撞:
for(int j = 0; j < i; j++) { //...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.