Java-检查MultiDimensional Array中的值

时间:2022-08-11 21:29:40

I am working on an assignment to create a tictactoe game using a multidimensional array, a separate class with methods to be invoked by the main class.

我正在编写一个使用多维数组创建tictactoe游戏的任务,这是一个单独的类,主类可以调用方法。

The array is 3 X 3 and is initialized to zero. When player 1 chooses a location on the board a 1 is put in that specific index. Then the prompt allows player 2 to make their selection. Each time a player takes their turn a method is invoked to check if the board is complete, if it is complete (filled with 1's and 2') then the game is called a draw. This method is not working as it should and it calls the game a draw sometimes on the second move. Here is my method i am using.

该数组为3 X 3并初始化为零。当玩家1选择棋盘上的位置时,将1放入该特定索引中。然后提示允许玩家2进行选择。每次玩家轮到一个方法时,会调用一个方法来检查棋盘是否完整,如果完成(用1和2'填充),则游戏称为平局。这种方法不能正常工作,它有时会在第二步中将游戏称为平局。这是我正在使用的方法。

public boolean isBoardComplete()
{
    // sets complete to true
    boolean complete = true;

    //will change complete to false
    for (int i = 0; i < 3; i++)
    {
        for(int j =0; j < 3; j++)
        {
            if (_board[i][j] == 0)
            {
                complete = false;
            }
        }
    }
    return complete;
}

6 个解决方案

#1


This code is not producing the problem. You need to make sure the board is initially filled with zeros before beginning the game. I would print out the board state to make sure this is the case. Otherwise, make sure you are using your boolean value correctly when you return it from this method.

此代码不会产生问题。在开始游戏之前,您需要确保电路板最初用零填充。我会打印出电路板状态以确保是这种情况。否则,请确保从此方法返回时正确使用布尔值。

#2


try this:

 public boolean isBoardComplete()
 {
   //will change complete to false
   for (int i = 0; i < 3; i++)
   {
     for(int j =0; j < 3; j++)
     {
        if (_board[i][j] == 0)
        {
            return false;
        }
     }
   }
  return true;
 }

#3


Looks like the problem is in the makeMove() method. Code is returning 'false' after making the move and from the code flow it is clear that the method should return 'true' for valid move.

看起来问题出在makeMove()方法中。代码在移动后返回'false',并且从代码流中可以清楚地看到该方法应该返回'true'以进行有效移动。

Try this

    public boolean makeMove( int row, int col) { 
        row = row - 1; col = col - 1;

        // Checks to see if board location is occupied and a move can be made
        if (_board[row][col] == 0)
        {
            _board[row][col] = _player;
            return true;
        }
        return false;

    }

#4


Is the array declared as an Integer array or an int array? This will make a difference if you are using the == and auto-unboxing (even though with small numbers they should be cached).

数组是声明为Integer数组还是int数组?如果您使用==和自动取消装箱,这将有所不同(即使数量较小,它们应该被缓存)。

Other than that, I would say that your array is not properly initialized. Post up the code that calls this method, and the code that initializes your array. The problem most likely resides in one of those two places.

除此之外,我会说你的阵列没有正确初始化。发布调用此方法的代码以及初始化数组的代码。问题很可能在于这两个地方之一。

#5


If you are using JAVA 5 or above ,you can use Arrays.deepEquals method.From the javadocs ,"this method is appropriate for use with nested arrays of arbitrary depth."

如果您使用的是JAVA 5或更高版本,则可以使用Arrays.deepEquals方法。从javadocs开始,“此方法适用于任意深度的嵌套数组。”

Example:-

  String[][] ticTacToe = { {"X", "O", "O"},
                             {"O", "X", "X"},
                             {"X", "O", "X"}};
    System.out.println(Arrays.deepToString(ticTacToe));

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

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

    if (Arrays.deepEquals(ticTacToe, ticTacToe2)) {
      System.out.println("Boards 1 and 2 are equal.");
    } else {
      System.out.println("Boards 1 and 2 are not equal.");
    }

    if (Arrays.deepEquals(ticTacToe, ticTacToe3)) {
      System.out.println("Boards 1 and 3 are equal.");
    } else {
      System.out.println("Boards 1 and 3 are not equal.");
    }
  }

#6


Here is my code. I have the main class (TicTacToeApplication) and the TTTboard class.

这是我的代码。我有主类(TicTacToeApplication)和TTTboard类。

import java.util.Scanner;

public class TicTacToeApplication {

    public static void main(String[] args)
    {
        // declare variables including our TTT board

        TTTBoard myGame = new TTTBoard();
        Scanner input = new Scanner(System.in);
        int row;
        int col;


        while(myGame.determineWinner() == 0 && !myGame.isBoardComplete())
        {

            myGame.displayBoard();


            System.out.println("Player " + myGame.getCurrentPlayer());
            System.out.println("Make your move.");
            System.out.print("Row please (1-3):");
            row = input.nextInt();


            while(row < 1 || row > 3)
            {
                System.out.println("Invalid Row.");
                System.out.print("Try again (1-3):");
                row = input.nextInt();
            }

            System.out.print("Col please (1-3):");
            col = input.nextInt();


            while(col < 1 || col > 3)
            {
                System.out.println("Invalid Col.");
                System.out.print("Try again (1-3):");
                col = input.nextInt();
            }

            // while the move is invalid make them make another move
            while(!myGame.makeMove(row, col))
            {
                System.out.println("Invalid Move... Try Again.");
                System.out.print("Row please (1-3):");
                row = input.nextInt();

                // error trap for valid row
                while(row < 1 || row > 3)
                {
                    System.out.println("Invalid Row.");
                    System.out.print("Try again (1-3):");
                    row = input.nextInt();
                }

                System.out.print("Col please (1-3):");
                col = input.nextInt();

                // error trap for valid col
                while(col < 1 || col > 3)
                {
                    System.out.println("Invalid Col.");
                    System.out.print("Try again (1-3):");
                    col = input.nextInt();
                }
            }
        }

        // if we left the loop because the boards full and there's no winner
        // it must be a cats game
        if (myGame.determineWinner() == 0)
        {
            System.out.println("Sorry - Cat's Game");
        }
        else
        {
            System.out.print("The Winner is Player ");
            if (myGame.getCurrentPlayer() == 1)
            {
                System.out.println("2");
            }
            else
            {
                System.out.println("1");
            }
        }
    }

}

public class TTTBoard
{

   private int [][] _board;
   private int _player;


   public TTTBoard ()
   {
       _player = 0;
       _board = new int [3][3];

       for (int row = 0; row < 3; row++)
       {    
           for(int column = 0; column < 3; column++)
           {
              _board[row][column] = 0;
           }
       }
    }


   public boolean makeMove( int row, int col)
   {
        row = row - 1;
        col = col - 1;

        // Checks to see if board location is occupied and a move can be made

        if (_board[row][col] == 0)
        {
            _board[row][col] = _player;
            return false;
        }
        else
        {
            return true;
        }
   }


   public boolean isBoardComplete ()
   {
       for (int row = 0; row < 3; row++)
       {
           for (int column = 0; column <3; column++)
           {
               if (_board [row][column] == 0)
               {
                   return false;
               }

           }
       }

       return true;
   }


   public int determineWinner ()
   {
        // First check rows and columns
          int winner = 0;

        // Check for winner in row 1
        if (_board[0][0] == _board[0][1] && _board[0][0] == _board[0][2] &&
                _board[0][0] != 0)
        {
            winner = _board[0][0];
        }

        // Check for winner in row 2
        if (_board[1][0] == _board[1][1] && _board[1][0] == _board[1][2] &&
                _board[1][0] != 0)
        {
            winner = _board[1][0];
        }

        // Check for winner in row 3
        if (_board[2][0] == _board[2][1] && _board[2][0] == _board[2][2] &&
                _board[2][0] != 0)
        {
            winner = _board[2][0];
        }

        // Check for winner in col 1
        if (_board[0][0] == _board[1][0] && _board[0][0] == _board[2][0] &&
                _board[0][0] != 0)
        {
            winner = _board[0][0];
        }

        // Check for winner in col 2
        if (_board[0][1] == _board[1][1] && _board[0][1] == _board[2][1] &&
                _board[0][1] != 0)
        {
            winner = _board[0][1];
        }

        // Check for winner in col 3
        if (_board[0][2] == _board[1][2] && _board[0][2] == _board[2][2] &&
                _board[0][2] != 0)
        {
            winner = _board[0][2];
        }

        // Check for winner in first diagonal
        if (_board[0][0] == _board[1][1] && _board[0][0] == _board[2][2] &&
                _board[0][0] != 0)
        {
            winner = _board[0][0];
        }
        // Check for winner in 2nd diagonal
        if (_board[2][0] == _board[1][1] && _board[2][0] == _board[0][2] &&
                _board[2][0] != 0)
        {
            winner = _board[2][0];
        }

        return winner;
    }


   public void displayBoard()
   {
        System.out.println();

        for (int r=0; r<_board.length; r++)
        {

            for (int c=0; c<_board[r].length; c++)
            {

                System.out.print(" " + _board[r][c]);
            }

            System.out.println("");
        }

   }


   public int getCurrentPlayer ()
   {
       if (_player == 0)
       {
            return _player = 1;
       }
       if (_player == 1)
       {
           return _player = 2;
       }
       else
       {
           return _player = 1;
       }

   }
}

#1


This code is not producing the problem. You need to make sure the board is initially filled with zeros before beginning the game. I would print out the board state to make sure this is the case. Otherwise, make sure you are using your boolean value correctly when you return it from this method.

此代码不会产生问题。在开始游戏之前,您需要确保电路板最初用零填充。我会打印出电路板状态以确保是这种情况。否则,请确保从此方法返回时正确使用布尔值。

#2


try this:

 public boolean isBoardComplete()
 {
   //will change complete to false
   for (int i = 0; i < 3; i++)
   {
     for(int j =0; j < 3; j++)
     {
        if (_board[i][j] == 0)
        {
            return false;
        }
     }
   }
  return true;
 }

#3


Looks like the problem is in the makeMove() method. Code is returning 'false' after making the move and from the code flow it is clear that the method should return 'true' for valid move.

看起来问题出在makeMove()方法中。代码在移动后返回'false',并且从代码流中可以清楚地看到该方法应该返回'true'以进行有效移动。

Try this

    public boolean makeMove( int row, int col) { 
        row = row - 1; col = col - 1;

        // Checks to see if board location is occupied and a move can be made
        if (_board[row][col] == 0)
        {
            _board[row][col] = _player;
            return true;
        }
        return false;

    }

#4


Is the array declared as an Integer array or an int array? This will make a difference if you are using the == and auto-unboxing (even though with small numbers they should be cached).

数组是声明为Integer数组还是int数组?如果您使用==和自动取消装箱,这将有所不同(即使数量较小,它们应该被缓存)。

Other than that, I would say that your array is not properly initialized. Post up the code that calls this method, and the code that initializes your array. The problem most likely resides in one of those two places.

除此之外,我会说你的阵列没有正确初始化。发布调用此方法的代码以及初始化数组的代码。问题很可能在于这两个地方之一。

#5


If you are using JAVA 5 or above ,you can use Arrays.deepEquals method.From the javadocs ,"this method is appropriate for use with nested arrays of arbitrary depth."

如果您使用的是JAVA 5或更高版本,则可以使用Arrays.deepEquals方法。从javadocs开始,“此方法适用于任意深度的嵌套数组。”

Example:-

  String[][] ticTacToe = { {"X", "O", "O"},
                             {"O", "X", "X"},
                             {"X", "O", "X"}};
    System.out.println(Arrays.deepToString(ticTacToe));

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

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

    if (Arrays.deepEquals(ticTacToe, ticTacToe2)) {
      System.out.println("Boards 1 and 2 are equal.");
    } else {
      System.out.println("Boards 1 and 2 are not equal.");
    }

    if (Arrays.deepEquals(ticTacToe, ticTacToe3)) {
      System.out.println("Boards 1 and 3 are equal.");
    } else {
      System.out.println("Boards 1 and 3 are not equal.");
    }
  }

#6


Here is my code. I have the main class (TicTacToeApplication) and the TTTboard class.

这是我的代码。我有主类(TicTacToeApplication)和TTTboard类。

import java.util.Scanner;

public class TicTacToeApplication {

    public static void main(String[] args)
    {
        // declare variables including our TTT board

        TTTBoard myGame = new TTTBoard();
        Scanner input = new Scanner(System.in);
        int row;
        int col;


        while(myGame.determineWinner() == 0 && !myGame.isBoardComplete())
        {

            myGame.displayBoard();


            System.out.println("Player " + myGame.getCurrentPlayer());
            System.out.println("Make your move.");
            System.out.print("Row please (1-3):");
            row = input.nextInt();


            while(row < 1 || row > 3)
            {
                System.out.println("Invalid Row.");
                System.out.print("Try again (1-3):");
                row = input.nextInt();
            }

            System.out.print("Col please (1-3):");
            col = input.nextInt();


            while(col < 1 || col > 3)
            {
                System.out.println("Invalid Col.");
                System.out.print("Try again (1-3):");
                col = input.nextInt();
            }

            // while the move is invalid make them make another move
            while(!myGame.makeMove(row, col))
            {
                System.out.println("Invalid Move... Try Again.");
                System.out.print("Row please (1-3):");
                row = input.nextInt();

                // error trap for valid row
                while(row < 1 || row > 3)
                {
                    System.out.println("Invalid Row.");
                    System.out.print("Try again (1-3):");
                    row = input.nextInt();
                }

                System.out.print("Col please (1-3):");
                col = input.nextInt();

                // error trap for valid col
                while(col < 1 || col > 3)
                {
                    System.out.println("Invalid Col.");
                    System.out.print("Try again (1-3):");
                    col = input.nextInt();
                }
            }
        }

        // if we left the loop because the boards full and there's no winner
        // it must be a cats game
        if (myGame.determineWinner() == 0)
        {
            System.out.println("Sorry - Cat's Game");
        }
        else
        {
            System.out.print("The Winner is Player ");
            if (myGame.getCurrentPlayer() == 1)
            {
                System.out.println("2");
            }
            else
            {
                System.out.println("1");
            }
        }
    }

}

public class TTTBoard
{

   private int [][] _board;
   private int _player;


   public TTTBoard ()
   {
       _player = 0;
       _board = new int [3][3];

       for (int row = 0; row < 3; row++)
       {    
           for(int column = 0; column < 3; column++)
           {
              _board[row][column] = 0;
           }
       }
    }


   public boolean makeMove( int row, int col)
   {
        row = row - 1;
        col = col - 1;

        // Checks to see if board location is occupied and a move can be made

        if (_board[row][col] == 0)
        {
            _board[row][col] = _player;
            return false;
        }
        else
        {
            return true;
        }
   }


   public boolean isBoardComplete ()
   {
       for (int row = 0; row < 3; row++)
       {
           for (int column = 0; column <3; column++)
           {
               if (_board [row][column] == 0)
               {
                   return false;
               }

           }
       }

       return true;
   }


   public int determineWinner ()
   {
        // First check rows and columns
          int winner = 0;

        // Check for winner in row 1
        if (_board[0][0] == _board[0][1] && _board[0][0] == _board[0][2] &&
                _board[0][0] != 0)
        {
            winner = _board[0][0];
        }

        // Check for winner in row 2
        if (_board[1][0] == _board[1][1] && _board[1][0] == _board[1][2] &&
                _board[1][0] != 0)
        {
            winner = _board[1][0];
        }

        // Check for winner in row 3
        if (_board[2][0] == _board[2][1] && _board[2][0] == _board[2][2] &&
                _board[2][0] != 0)
        {
            winner = _board[2][0];
        }

        // Check for winner in col 1
        if (_board[0][0] == _board[1][0] && _board[0][0] == _board[2][0] &&
                _board[0][0] != 0)
        {
            winner = _board[0][0];
        }

        // Check for winner in col 2
        if (_board[0][1] == _board[1][1] && _board[0][1] == _board[2][1] &&
                _board[0][1] != 0)
        {
            winner = _board[0][1];
        }

        // Check for winner in col 3
        if (_board[0][2] == _board[1][2] && _board[0][2] == _board[2][2] &&
                _board[0][2] != 0)
        {
            winner = _board[0][2];
        }

        // Check for winner in first diagonal
        if (_board[0][0] == _board[1][1] && _board[0][0] == _board[2][2] &&
                _board[0][0] != 0)
        {
            winner = _board[0][0];
        }
        // Check for winner in 2nd diagonal
        if (_board[2][0] == _board[1][1] && _board[2][0] == _board[0][2] &&
                _board[2][0] != 0)
        {
            winner = _board[2][0];
        }

        return winner;
    }


   public void displayBoard()
   {
        System.out.println();

        for (int r=0; r<_board.length; r++)
        {

            for (int c=0; c<_board[r].length; c++)
            {

                System.out.print(" " + _board[r][c]);
            }

            System.out.println("");
        }

   }


   public int getCurrentPlayer ()
   {
       if (_player == 0)
       {
            return _player = 1;
       }
       if (_player == 1)
       {
           return _player = 2;
       }
       else
       {
           return _player = 1;
       }

   }
}