我没有遇到任何编译错误,但是由于我的checkWinner方法甚至没有遇到,所以必须有一个逻辑错误。

这是我的checkWinner方法的代码:

  public boolean checkWinner() {
  for (int i=0;i<3;i++){
     if ((gameBoard[i][0] == gameBoard[i][1]) && (gameBoard[i][1] == gameBoard[i][2])) { //check every row to find a match
        System.out.println(currentMark + "wins!");
     }
     else if ((gameBoard[0][i] == gameBoard[1][i]) && (gameBoard[1][i] == gameBoard[2][i])) { //checks every column to find a match
        System.out.println(currentMark + "wins!");
     }
  }
  if ((gameBoard[0][0] == gameBoard[1][1]) && (gameBoard[1][1] == gameBoard[2][2])) { //checks first diagonal
     System.out.println(currentMark + "wins!");
  }
  else if ((gameBoard[0][2] == gameBoard[1][1]) && (gameBoard[1][1] == gameBoard[2][0])) { //checks second diagonal
     System.out.println(currentMark + "wins!");
  }
  else
     System.out.println("Tie!");
  return true;


}

这是我的游戏方法,在用户输入动作后,我每次都使用checkWinner检查赢家。

   public void letsPlay() {
  while (true) {
     displayBoard();
     gameOptions();
     int choice = input.nextInt();
     if (choice == 1) {
        if (addMove(input.nextInt(),input.nextInt())) {
           displayBoard();
           checkWinner();
           whoseTurn();

           System.exit(0);
        }


我不确定我的checkWinners方法是否应该是我的addMove方法的一部分...这是addMove

   public boolean addMove(int row, int column) {
  boolean nonacceptable = true;
  while (nonacceptable) {
     System.out.println("Which row and column would you like to enter your mark? Enter the row and column between 0 and 2 separated by a space.");
     row = input.nextInt();
     column = input.nextInt();
     if ((row >= 0 && row <=2) && (column >= 0 && column <=2)) { //make sure user entered a number between 0 and 2
        if (gameBoard[row][column] != ' ') {
           System.out.println("Sorry, this position is not open!");
        }
        else {
           gameBoard[row][column] = currentMark;
           nonacceptable = false;
        }
     }
     else
        System.out.println("That position is not between 0 and 2!");
     }
     return nonacceptable;


}

我如何将其合并到addMove方法中或对其进行更改,以使其作为自己的方法工作?

最佳答案

看起来当用户输入有效答案时,nonacceptable设置为false,从而退出while(nonacceptable)循环。但是然后您返回nonacceptable(这是错误的),这意味着检查if (addMove())将不通过(因此不会调用checkWinner)。您可以尝试将if语句向下移动,如下所示:

addMove();
displayBoard();
if (checkWinner()) {
    System.exit(0);
}
whoseTurn();


但是,只有在比赛获胜或平局的情况下,您才需要更改checkWinner以返回true,否则返回false

07-25 20:13