在java中遇到循环问题

时间:2016-11-29 01:31:07

标签: java arrays loops

我正致力于为一个程序生成的地图播种,但是当我去运行它时它只是在后台工作时应该显示一个带有不同颜色方块的地图。我需要帮助的方法在地图上选择一些随机位置并指定一个随机类型作为起点。

这是整个方法

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

我确定它是一个无限循环,但我没有看到它,感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

每次都会发生这种情况

else{
  i--;
}

所以for循环永远不会增加并完成

也许当你这样做时(每次都会发生,所以检查i != j

error = 1;

你想打破

答案 1 :(得分:0)

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初始化事物的方式,但它仍然是垃圾 - 它包含任意(虽然决定性)值,< strong>不第二个种子的实际坐标(尚未创建!)

您应该只检查与之前迭代中创建的种子的碰撞:

for(int j = 0; j < i; j++) { //...