【发布时间】:2020-02-24 12:24:27
【问题描述】:
每当玩家输入数字时,我都会尝试更新我的棋盘(由数组列表中的三个数组列表组成)。数字对应于棋盘上的一个正方形,方式如下:
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;
}
}
问题在于,当用户输入一个值时,该值对应的整个列都会更新,而不是单个方块。
我已经检查过了:
- 只触发了一个 if 语句。
- 更新只发生一次
- 更新发生在正确的索引上。
通过我的调试,我认为问题线是:
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;
}
【问题讨论】:
-
使用一个固定长度的二维数组 [3][3] 它会更容易访问,因为你不会改变大小(这就是 List 的用途)
-
你能不能也展示一下你的
display方法? -
乍一看,您的代码似乎没问题,尽管它可以进行一些改进。显示您的
display方法,这可能是罪魁祸首。 -
我认为您最好使用一维列表,因为您已经在使用索引 1 到 9。管理起来会更容易
-
"我相信问题是:updateRow.set(choice-1, val);"不,绝对不是。你的代码没问题,显示最终板一定是你的错误。
标签: java arrays list arraylist