亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

更新 ArrayList

更新 ArrayList

DIEA 2024-01-05 10:44:59
每當玩家輸入數字時,我都會嘗試更新我的棋盤(由數組列表中的三個數組列表組成)。該數字與棋盤上的一個正方形的對應關系如下:1 2 34 5 67 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;    }}問題在于,當用戶輸入一個值時,該值對應的整個列都會更新,而不是單個方塊。我已經檢查過:只有一個 if 語句被觸發。更新僅發生一次更新發生在正確的索引上。通過我的調試,我認為問題所在是:updateRow.set(choice-1, val);當用戶(玩家1)輸入1時:預期輸出| X || - || - | | - || - || - | | - || - || - |實際產量| X || - || - | | X || - || - | | X || - || - |顯示功能抱歉,我沒有意識到你們需要看到這個其他功能
查看完整描述

2 回答

?
繁花不似錦

TA貢獻1851條經驗 獲得超4個贊

問題似乎出現在創建中:您可能為每一行使用相同的列 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];


查看完整回答
反對 回復 2024-01-05
?
侃侃無極

TA貢獻2051條經驗 獲得超10個贊

我已經使用了您的代碼并添加了顯示功能,它給了我預期的輸出。我想您可能需要檢查顯示功能或創建板的方式。下面是我使用的顯示功能


 public static String display(ArrayList<ArrayList<String>> board) {

     String output = "";

     for(ArrayList<String> list : board) {

         for(String s:list){

             output += s ;

         }

         output += "\n";

     }

     return output;


 }


查看完整回答
反對 回復 2024-01-05
  • 2 回答
  • 0 關注
  • 183 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號