int randRow = rand.nextInt(rows-4);
int randColumn = rand.nextInt(columns);
我在这里检查我的新船是否不会干扰我的第一艘船。整个数组都填充了包含'。'的对象。 char除了第一艘船的位置
if(field[randRow][randColumn].value == '.' &&
field[randRow][randColumn+1].value == '.' &&
field[randRow][randColumn+2].value == '.' &&
field[randRow][randColumn+3].value == '.'){
field[randRow][randColumn] = new Square('b');
field[randRow+1][randColumn] = new Square('b');
field[randRow+2][randColumn] = new Square('b');
field[randRow+3][randColumn] = new Square('b');
} else{
如果我的新船不合适,我想用不同的随机值重试,但我不知道如何。
答案 0 :(得分:6)
基本上你不确定如何再次生成随机数。只需使用下面的内容
while(true) {
//generate random number here
if (can place battleship) {
place battleship
break //placed battleship so no need to retry. stop retrying
}
//else we will loop till we can place the battleship
}