John
John

Reputation: 145

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
  }

Upvotes: 0

Views: 104

Answers (2)

JBKM
JBKM

Reputation: 116

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];
}

Upvotes: 3

Elliott Frisch
Elliott Frisch

Reputation: 201399

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.

Standard Chessboard

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];

Upvotes: 0

Related Questions