ArrayListのを更新します

ライラオーウェル:

私は、プレイヤーが番号を入力する時はいつでも(ArrayListの中3つのArrayListからなる)私のボードを更新しようとしています。以下の方法でボード上の正方形の数の対応:

1 2 3
4 5 6
7 8 9

私はトラブルグリッドを更新したのです。

関数

public static void playBoard(int choice, ArrayList<ArrayList<String>> board, boolean playerTurn) {
    String val;
    if (!playerTurn) {
        val = "| X |";
    }
    else {
        val = "| O |";
    }
    if (choice>=1 && choice<=3) {
        System.out.println("H");
        ArrayList<String> updateRow = board.get(0);
        if (choice ==3) {
            val+="\n";
        }
        updateRow.set(choice-1, val);
        System.out.println(updateRow);
        board.set(0, updateRow);
        System.out.println(display(board));
    }
    else if (choice>=4 && choice<=6) {
        System.out.println("H");
        ArrayList<String> updateRow = board.get(1);
        if (choice ==6) {
            val+="\n";
        }
        updateRow.set((choice-4), val);
        board.set(1, updateRow);
        System.out.println(display(board));
    }
    else if (choice>=7 && choice<=9) {
        System.out.println("H");
        ArrayList<String> updateRow = board.get(2);
        if (choice ==9) {
            val+="\n";
        }
        updateRow.set(choice-7, val);
        board.set(2, updateRow);
        System.out.println(display(board));
    }
    else {
        System.out.println("Input out of range");
        return;
    }
}

問題ではなく、個々の正方形の更新された全体の列の値が対応していることをユーザが値を入力することです。

私はそれをチェックしています

  • 文がトリガされた場合のみ、1。
  • 更新は1回だけ発生します
  • 更新は正しい指標時に起こります。

私のデバッグを通じ、私は問題の行があると考えています。

updateRow.set(choice-1, val);

ユーザー(プレイヤー1)は1を入力すると:

予想される出力

| X || - || - |
| - || - || - |
| - || - || - |

実際の出力

| X || - || - |
| X || - || - |
| X || - || - |

表示機能

申し訳ありませんが、私は、この他の機能を確認するために必要な君たちを実現していませんでした

    public static String display(ArrayList<ArrayList<String>> board) {
    StringBuilder builder = new StringBuilder();
    for (ArrayList<String> row : board) {
        for (String space: row) {
            builder.append(space);
        }
    }
    String text = builder.toString();
    return text;
}
ジョープEggen:

問題は、作成に思える:あなたはおそらく、すべての行に対して同じ列のArrayListオブジェクトを使用していました。

// Error:
ArrayList<String> row = new ArrrayList<>();
row.add("...");
row.add("...");
row.add("...");
for (int i = 0; i < 3; ++i) {
    board.add(row);
}

になるはずだった:

for (int i = 0; i < 3; ++i) {
    ArrayList<String> row = new ArrrayList<>();
    row.add("...");
    row.add("...");
    row.add("...");
    board.add(row);
}

同じ概念エラー手段:行うために必要されていません。

board.set(2, updateRow); // Not needed.

ボードが保有するにupdateRowオブジェクト内のエントリを変更することは、参照によって行われます。

いくつかのヒント:

  • ここで一つは使用することができますString[][]
  • ので、多分、(文字?)データモデルからディスプレイ/ビュー(文字列)を分離する方が簡単です char[][] board = new char[3][3];

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=330734&siteId=1