英文:
Android Studio: Java: Populating 2D Array with buttons using IDs
问题
以下是翻译好的部分:
我正在尝试使用按钮来填充一个二维数组,以创建一个大小为5x5的井字棋类型游戏。
到目前为止,我想出了以下代码:(目前无效)
private Button[][] gameArray = new Button[5][5];
for (int x = 0; x < 5; x++) {
for (int y = 0; y < 5; y++) {
String gameButtonId = "buttons" + x + y;
int gameID = getResources().getIdentifier(gameButtonId, "id", getPackageName());
gameArray[x][y] = findViewById(gameID);
gameArray[x][y].setOnClickListener(this);
}
}
我已经创建了具有特定ID的按钮,如下所示:
第一行的按钮ID为:buttons00、buttons01、buttons02、buttons03、buttons04,
第二行为:buttons10、buttons11、buttons12、buttons13、buttons14,依此类推,直到网格上有25个按钮。
我应该如何有效地使用这些按钮及其ID填充二维数组?
英文:
I am trying to populate a 2d array with buttons for the purpose of creating a tic tac toe type of game, that is 5x5 in size.
So far I have come up with this: (Not working)
private Button[][] gameArray = new Button[5][5];
for (int x = 0; x<5; x++) {
for (int y = 0; x < 5; y++) {
String gameButtonId = "buttons" + x + y;
int gameID = getResources().getIdentifier(gameButtonId, "id", getPackageName());
gameArray[x][y] = findViewById(gameID);
gameArray[x][y].setOnClickListener(this);
I have created the buttons with specific ids as follows:
the first row has button ids: buttons00, buttons01, buttons02, buttons03, buttons04,
the second row is: buttons10, buttons11, buttons12, buttons 13, buttons14 and so on.. until there is 25 buttons on the grid.
How would I effectively populate the 2d array using these buttons and their ids?
答案1
得分: 0
你的内部循环有问题!你正在运行直到 x < 5
,但应该是 y < 5
才对!
你的代码应该像这样:
private Button[][] gameArray = new Button[5][5];
for (int x = 0; x < 5; x++) {
for (int y = 0; y < 5; y++) {
String gameButtonId = "buttons" + x + y;
int gameID = getResources().getIdentifier(gameButtonId, "id", getPackageName());
gameArray[x][y] = findViewById(gameID);
gameArray[x][y].setOnClickListener(this);
}
}
英文:
Your inner- loop is wrong! You're running until x < 5
, but it should be y < 5
instead!
Your code should look like this:
private Button[][] gameArray = new Button[5][5];
for (int x = 0; x < 5; x++) {
for (int y = 0; y < 5; y++) {
String gameButtonId = "buttons" + x + y;
int gameID = getResources().getIdentifier(gameButtonId, "id", getPackageName());
gameArray[x][y] = findViewById(gameID);
gameArray[x][y].setOnClickListener(this);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论