我不知道如何更改数组中的数组元素。
public class testOut{
public static void main(String[] args) {
String board[][] = generate(7,7);
print(board); // prints a 7x7 table with 49 "O"s
board[2][2] = "X"; // This is the line I'm concerned about
System.out.println(board[2][2]); // prints out "X"
System.out.println(board[1][1]); // prints out "Null"
print(board); // still prints a 7x7 table with 49 "O"s
}
static String[][] generate(int row, int column){
String[][] board = new String[row+1][column+1];
for (int x=0; x < row; x++){
for (int y=0; y < column; y++){
board[row][column] = "#";
}
}
return board;
}
static void print(String[][] board){
int row = board.length - 1;
int column = board[0].length - 1;
for (int x=0; x < row; x++){
for (int y=0; y < column; y++){
System.out.print(board[row][column]);
}
System.out.println("");
}
}
}
输出:
OOOOOOO
OOOOOOO
OOOOOOO
OOOOOOO
OOOOOOO
OOOOOOO
OOOOOOO
X
null
OOOOOOO
OOOOOOO
OOOOOOO
OOOOOOO
OOOOOOO
OOOOOOO
OOOOOOO
我正在尝试弄清楚 -
为什么我可以打印“X”,但我的打印功能却无法在 table 上打印“X”?
和
为什么我的代码能够正确打印出引用每个部分的表格,但是当我尝试打印单个元素时,它给出 null?
我猜这两个问题是相关的。它在 for 循环中工作,但不在循环之外。
最佳答案
阵列正在正确更新。这是你的打印错误。
它正在打印最后一行、最后一列。请注意循环中的 x
和 y
是如何未被使用的:
System.out.print(board[row][column]);
您可以使用循环计数器打印为:
System.out.print(board[x][y]);
关于java - 在 Java 中更改数组内的数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40834452/