关于FOR循环处理将1D数组转换为2D数组

时间:2018-12-12 03:24:14

标签: java arrays for-loop processing

我正在我的计算机科学课上使用处理井字游戏。在我的程序中,我正在对3行检查器进行编码,并且尝试使用2D数组代码对此进行编码,因为在对X / O进行编码时,我的数组已初始化为2D数组。此外,老师还给了我们一个该示例的代码但是是在1D数组中进行的,因此我不知道如何将他关于FOR循环的示例转换为2D,以便它可以运行到我的程序中。我已经将数组代码转换为适用于我的程序,并且该程序正在运行,但是有关有人是否获胜的代码(FOR循环)不起作用。有人能帮我吗?

void onlyX() { //views only X pieces, runs checker for onlyX (attempted to 
convert to 2D array form)
    for (int i=0; i<3; i++) {
      for (int j=0; j<3; j++) {
        if (boardPiece[i][j] == "X") {
          onlyXPiece[i][j] = "X";
        }
      }
    }
  }

  /*void onlyX() { //1D Form 
    for (int i=0; i<numberOfBoardPieces; i++) {
      if (boardPiece[i] == "X") {
        onlyXPiece[i] = "X";
      }
    }
  }*/

void onlyO() { //views only O pieces, runs checker for onlyO (attempted to 
convert to 2D array form)
   for (int i=0; i<3; i++) {
     for (int j=0; j<3; j++) {
       if (boardPiece[i][j] == "O") {
         onlyOPiece[i][j] = "O";
        }
      }
    }
  }

  /*void onlyO() { //1D form
    for (int i=0; i<numberOfBoardPieces; i++) {
      if (boardPiece[i] == "O") {
        onlyOPiece[i] = "O";
      }
    }
  }*/

2 个答案:

答案 0 :(得分:2)

您的2D数组FOR循环(通常称为double FOR LOOP)看起来不错,尽管我不太明白为什么您会将X和O放在单独的2D数组中。有多种检查获胜条件的方法,但这似乎过于复杂。

我在代码顶部改写了double for循环,以执行易于理解且可用于X和O的胜利检查。不要忘记您还必须检查垂直和对角线胜利。

String[][] boardPiece = {{"X", "", "O"}, 
                         {"O", "O","O"}, 
                         {"X", "", "X"}};

void setup() {
  println("X wins = "+ str(checkRows("X")));
  println("O wins = "+ str(checkRows("O")));
}

boolean checkRows(String XorO) { 
  for (int i=0; i<3; i++) { //for every row
    boolean win = true;     //set win to true
    for (int j=0; j<3; j++) { //for every column    
      if (boardPiece[i][j] != XorO) {  //if the column does not equal the sign that you are checking
        win = false;                   // meaning its the other, or it's empty, then set win to false
      }                                
    }
    if (win) {
      return true;    //if win is true, then there are 3 X's or 3 O's in this row, so return true
    }
  }
  return false;      // if none of the rows contain 3 equal, return false
}

答案 1 :(得分:2)

要检查是否有人赢得了比赛,您必须检查列,行和对角线。用一个参数编写一个checkBoard函数,您可以在其中指定要检查的片段类型("X" pr "O"

boolean checkBoard(String p) {

    boolean won = false;

    // check rows and columns
    for (int i=0; !won && i<3; i++) {
        boolean eqRow = true;
        boolean eqCol = true;
        for (int j=0; j<3; j++) {
            eqRow = eqRow && boardPiece[i][j] == p;
            eqCol = eqCol && boardPiece[j][i] == p;
        }
        won = eqRow || eqCol;
    }

    // check diagonals
    if ( !won )
    {
        boolean d1 = true;
        boolean d2 = true;
        for (int i=0; !won && i<3; i++) {
            d1 = d1 && boardPiece[i][i] == p;
            d2 = d2 && boardPiece[2-i][i] == p;
        }
        won = d1 || d2;
    }

    return won;
}