简体   繁体   中英

How do I use Java constructors to instantiate an array?

I have a constructor for a class that will simulate the knight's tour in java. Right now, the constructor takes in the starting row and column. I was wondering if there was a way it could take in the board size (total rows, total columns)? I am rather new to java and don't fully understand arrays so any help would be greatly appreciated!

public KnightsTour(int startRow, int startCol)
  {
    myBoard = new int[9][9];
    myCheckList = new int[9]; // myCheckList initialized with all 0
    myRandomMove = new Random();

    myMoveNumber = 1;

    // myRow and myCol start at (1,1)
    myRow = startRow;
    myCol = startCol;
    myBoard[myRow][myCol] = myMoveNumber;  // gets the board started
  }

You can use any integer type expression in the array constructor which includes variable references. Therefore, you can add two more parameters to the constructor for your class which specify the board size:

public KnightsTour(int startRow, int startCol, int height, int width) {
  myBoard = new int[height][width];
}
A Chessboard has 64 Spaces, and is Composed of 8 files and 8 ranks

Java arrays start at 0, the above code is designed to start at 1. Given that 9-1 is 8 there are eight spaces in myBoard = new int[9][9]; . One for every rank and file on a chess board.

标准棋盘

To pass that in and still use offset by one array indexes (if you must), that might look something like

 public KnightsTour(int startRow, int startCol, int ranks, int files) { myBoard = new int[ranks + 1][files + 1]; myCheckList = new int[ranks + 1]; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM