我有一个类的构造函数,它将在java中模拟骑士之旅。现在,构造函数接受起始行和列。我想知道是否有办法可以接受板的大小(总行数,总列数)?我对 java 相当陌生,不完全理解数组,因此我们将不胜感激!
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
}
最佳答案
您可以在数组构造函数中使用任何包含变量引用的整数类型表达式。因此,您可以在类的构造函数中添加两个参数来指定板尺寸:
public KnightsTour(int startRow, int startCol, int height, int width) {
myBoard = new int[height][width];
}
关于java - 如何使用 Java 构造函数实例化数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30447386/