Android Studio:Java:使用ID填充2D按钮数组

huangapple go评论94阅读模式
英文:

Android Studio: Java: Populating 2D Array with buttons using IDs

问题

以下是翻译好的部分:

我正在尝试使用按钮来填充一个二维数组,以创建一个大小为5x5的井字棋类型游戏。

到目前为止,我想出了以下代码:(目前无效)

  1. private Button[][] gameArray = new Button[5][5];
  2. for (int x = 0; x < 5; x++) {
  3. for (int y = 0; y < 5; y++) {
  4. String gameButtonId = "buttons" + x + y;
  5. int gameID = getResources().getIdentifier(gameButtonId, "id", getPackageName());
  6. gameArray[x][y] = findViewById(gameID);
  7. gameArray[x][y].setOnClickListener(this);
  8. }
  9. }

我已经创建了具有特定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)

  1. private Button[][] gameArray = new Button[5][5];
  2. for (int x = 0; x&lt;5; x++) {
  3. for (int y = 0; x &lt; 5; y++) {
  4. String gameButtonId = &quot;buttons&quot; + x + y;
  5. int gameID = getResources().getIdentifier(gameButtonId, &quot;id&quot;, getPackageName());
  6. gameArray[x][y] = findViewById(gameID);
  7. 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 才对!

你的代码应该像这样:

  1. private Button[][] gameArray = new Button[5][5];
  2. for (int x = 0; x < 5; x++) {
  3. for (int y = 0; y < 5; y++) {
  4. String gameButtonId = "buttons" + x + y;
  5. int gameID = getResources().getIdentifier(gameButtonId, "id", getPackageName());
  6. gameArray[x][y] = findViewById(gameID);
  7. gameArray[x][y].setOnClickListener(this);
  8. }
  9. }
英文:

Your inner- loop is wrong! You're running until x &lt; 5, but it should be y &lt; 5 instead!

Your code should look like this:

  1. private Button[][] gameArray = new Button[5][5];
  2. for (int x = 0; x &lt; 5; x++) {
  3. for (int y = 0; y &lt; 5; y++) {
  4. String gameButtonId = &quot;buttons&quot; + x + y;
  5. int gameID = getResources().getIdentifier(gameButtonId, &quot;id&quot;, getPackageName());
  6. gameArray[x][y] = findViewById(gameID);
  7. gameArray[x][y].setOnClickListener(this);

huangapple
  • 本文由 发表于 2020年10月9日 04:57:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/64270486.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定