gpt4 book ai didi

java - 在 Java 中更改数组内的数组元素

转载 作者:行者123 更新时间:2023-12-02 03:12:32 24 4
gpt4 key购买 nike

我不知道如何更改数组中的数组元素。

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 循环中工作,但不在循环之外。

最佳答案

阵列正在正确更新。这是你的打印错误。

它正在打印最后一行、最后一列。请注意循环中的 xy 是如何未被使用的:

System.out.print(board[row][column]);

您可以使用循环计数器打印为:

System.out.print(board[x][y]);

关于java - 在 Java 中更改数组内的数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40834452/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com