私は2Dアレーを使って戦艦ゲームを作っています。私のdo-whileループが必要です。すでに船がある場所に船を置くと、再び船を置くよう求められます。以下は、配列の値を0から1に変更して船の配置に似たコードです。あなたはこれは、彼らが船の特定のタイプを配置する場所をユーザーに促し異なるクラスのコードですでに1なぜdo-whileループは機能しないのですか?
public int[][] changeMatrixValues(int i, int j, int k, int l) throws IllegalArgumentException { // for a ship with dimensions k*l and starting grid[i][j]
for (mRow = i; mRow < (i + k); mRow++) {
for (mCol = j; mCol < (j + l); mCol++) {
if (mMatrix[mRow][mCol] == 0 && mMatrix[mRow][mCol] != 1)
mMatrix[mRow][mCol] = 1;
else
throw new IllegalArgumentException("Ship already in area");
}
}
return mMatrix;
}
の価値がある船を配置しようとした場合には、IllegalArgumentExceptionをスローします。これはIllegalArgumentExceptionをピックアップしますが、do-whileループは機能しません。ユーザーが別の船の上に船を置くと、その特定の船を置く別の機会は得られません。次の船を置く。なぜ誰かがこのdo-whileループがうまくいかない理由を強調できればそれはすばらしいだろう!
あなたは1に配列の値を設定すると、IllegalArgumentExceptionをスローした場合、あなたがそれらをロールバックしていないメソッドchangeMatrixValuesでprivate boolean keepPlacing;
private void ship(String shipToPlace, Matrix matrix, int k, int l) {
keepPlacing = true;
do {
try {
System.out.println(shipToPlace);
chooseGrid(); // enter co-ords of where you want to place ship
matrix.changeMatrixValues(mRow, mCol, k, l);
keepPlacing = false;
} catch (IllegalArgumentException ie) {
System.out.println(ie.getMessage());
}
} while (keepPlacing);
matrix.printLabeledMatrix();
}
OK。最初は上手く見えます。あなたは 'catch'節で' keepPlacing'の値をデバッグして参照できますか? – MordechayS
'changeMatrixValues'には失敗したアトミック性がないことを指摘しておきましょう。「変更」全体が有効になっていることを確認するのではありません。これは、1つまたは複数のセルを設定してから失敗し、オブジェクトを破損状態にしておくことを意味します。 –
また、 'mMatrix [mRow] [mCol] == 0 && mMatrix [mRow] [mCol]!= 1'は' 0!= 1'なので冗長です。 –