每当玩家输入一个数字时,我正试图更新我的董事会(包括一个数组中的三个数组列表)。该数字对应于板上的正方形,其方式如下:
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;
}
}问题是,当用户输入一个值时,值对应的整个列将被更新,而不是单个正方形。
我已经核实过:
通过我的调试,我相信问题线是:
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;
}发布于 2019-10-29 10:51:04
问题似乎出现在创建过程中:您可能对每一行都使用相同的列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];。
发布于 2019-10-29 09:49:36
我使用了您的代码并添加了显示功能,它给了我预期的输出。我想您可能需要检查显示功能或创建板的方式。下面是我使用的显示函数
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;
}https://stackoverflow.com/questions/58604443
复制相似问题