有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在二维数组中检查一个元素是否跟在同一个元素后面n次

我正在为我的CS课程创建这个项目,它模仿了Tic Tac趾板。它对原来的3x3正方形效果很好,但现在我需要让程序询问用户他们希望它有多大。它只能是3x3到14x14的正方形。我也在问他们想要赢得这场比赛的连接数或连续的X或O数。连接只能等于或小于大小,但不能小于3

对于检查一行中水平x或o的条件,最初是这样的

for(int r = 0; r < 3; r++) {
  for(int c = 0; c < 1; c++) {
    if(board[r][c] == Cell.X && board[r][c + 1] == Cell.X && board[r][c + 2] == Cell.X) {
        return GameStatus.X_WON;
    }
    else if(board[r][c] == Cell.O && board[r][c + 1] == Cell.O && board[r][c + 2] == Cell.O) {
        return GameStatus.O_WON;
    }
  }
}

我已经让程序为连接和电路板尺寸输入数据

int connections;
SuperTicTacToe.getSize();

我写了这个

private GameStatus isWinner() {
  int count = 0;
  for(int r = 0; r < SuperTicTacToe.getSize(); r++) {
    for(int c = 0; c < 1; c++) {
      for(int i = 0; i < connections; i++){
        if(board[r][c + i] == Cell.X ){
           count++;
        }
        if(count == connections){
           return GameStatus.X_WON;
        }
      }
    }
  }
}

但我似乎唯一不能做的事情就是让程序以某种方式检查一行中的是否有x或o的连接号。它似乎只检查电路板上是否有连接x的数量,而不计算最后一列中的任何内容

是否有方法检查一行中的一个元素是否等于它前面的同一个元素的次数


共 (1) 个答案

  1. # 1 楼答案

    在写下代码之前,最好先画出你作为一个人用来解决这个问题的方法。如果你曾经在课堂上学习过代码,你就会知道白板是多么重要

    // This program pretends board is a boolean[][] array
    boolean horizontalFlag = true; // Assume that it is a 3 in a row
    boolean verticalFlag = true; // If it is proven not to be, then change to false
    for(int i=0; i<3; i++){
        for(int j=0; j<3; j++){
            if(!(board[i][j])) verticalFlag = false; // These methods draw horizontal and vertical lines
            if(!(board[j][i])) horizontalFlag = false; //i.e.
        }
    }
    /* What the code does, visualized.
    Horizontal check = h vertical check = v both = b none = 0
    This is based on each iteration of i.
     i=0   i=1   i=2
    b h h|0 v 0|0 0 v
    v 0 0|h b h|0 0 v
    v 0 0|0 v 0|h h b
    */
    if(board[1][1]) { // Diagonals
        if(board[0][0] && board[2][2]) return true; 
        if(board[2][0] && board[0][2]) return true; 
    }
    if(horizontalFlag||verticalFlag) return true; // If the flags "say" that there are straight lines
    

    请注意,此代码与您的程序不直接兼容