问题:我想在网格上生成接触的随机位置。位置总数为 5。是否有更有效/不同的方法来执行以下代码:
/*
* 8 1 2
* 7 [original] 3
* 6 5 4
*/
int rand = 1 + (int)(Math.random() * ((8 - 1) + 1));
if(rand >= 2 && rand<= 4)
{
newx++;
}
else if(rand >=6 && rand<=8)
{
newx--;
}
//change y according to number
if(rand == 8 || rand == 1 || rand==2)
{
newy++;
}
else if(rand >= 4 && rand<= 6 )
{
newy--;
}
最佳答案
根据this Thread switch
语句似乎对您的情况更有效。它还使您的代码更具可读性。
switch (rand){
case 1: newy++; break;
case 2: newx++; newy++; break;
case 3: newx++; break;
case 4: newx++; newy--; break;
case 5: newy--; break;
case 6: newx--; newy--; break;
case 7: newx--; break;
case 8: newx--; newy++; break;
}
关于java - 生成与二维数组中最后一组数字仅相差 1 的数字组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35015103/