简体   繁体   English

如何使用Java构造函数实例化数组?

[英]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. 我有一个类的构造函数,它将模拟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! 我对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
  }

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 棋盘有64个空格,由8个文件和8个等级组成

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]; Java数组从0开始,上面的代码从1开始。假设9-18 ,则myBoard = new int[9][9];有8个空格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]; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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