我正在为一个编程类做一个任务,涉及一个Knight巡演的启发式。目前我有一个方法,用于填充8x8棋盘阵列,其中“Board”对象知道棋盘上该空间的“可访问性”,以及之前是否实际访问过该棋盘。但是,当我创建8x8数组并尝试为此数组调用我的“fill”方法时,我得到一个错误,告诉我该数组在我正在使用的包中不存在...我在这里做错了什么?它不应该像声明数组和使用
调用方法一样简单Board [][] chessboard = new Board [8][8];
chessboard.fill();
或者我的语法错了?这里的参考是我的代码,它创建我的Board对象,我的可访问性矩阵,然后将这些可访问性值复制到我的8x8阵列上的每个Board对象。谢谢!
public class Board {
/*
* Initialize array that emulates chessboard. Will be 8x8, each space will
* contain the number of squares from which that space can be reached. The
* knight will start at a new space each tour and choose each move based on
* the "accessability" of each square within its "move pool". The knight
* will move to the square with least accesibility each time. When the
* Knight is moved to a square, this square will be marked as visited so
* that it cannot be visited again. Also, any space that could have been
* moved to but was not will have its accesability reduced by 1.
*/
private boolean visited;
private int accessValue;
private Board [][] chess = new Board[8][8];
public Board(int acessability, boolean beenVisited)
{
visited = beenVisited;
accessValue = acessability;
}
int [][] accessMatrix = {{2,3,4,4,4,4,3,2},
{ 3,4,6,6,6,6,4,3 },
{ 4,6,8,8,8,8,6,4 },
{ 4,6,8,8,8,8,6,4 },
{ 4,6,8,8,8,8,6,4 },
{ 4,6,8,8,8,8,6,4 },
{ 3,4,6,6,6,6,4,3 },
{ 2,3,4,4,4,4,3,2}};
public void fill()
{
for (int i = 0 ; i < accessMatrix.length ; i++)
{
chess[0][i].changeAccess(accessMatrix[0][i]);
}
for (int i = 0 ; i < accessMatrix.length ; i++)
{
chess[1][i].changeAccess(accessMatrix[1][i]);
}
for (int i = 0 ; i < accessMatrix.length ; i++)
{
chess[2][i].changeAccess(accessMatrix[2][i]);
}
for (int i = 0 ; i < accessMatrix.length ; i++)
{
chess[3][i].changeAccess(accessMatrix[3][i]);
}
for (int i = 0 ; i < accessMatrix.length ; i++)
{
chess[4][i].changeAccess(accessMatrix[4][i]);
}
for (int i = 0 ; i < accessMatrix.length ; i++)
{
chess[5][i].changeAccess(accessMatrix[5][i]);
}
for (int i = 0 ; i < accessMatrix.length ; i++)
{
chess[6][i].changeAccess(accessMatrix[6][i]);
}
for (int i = 0 ; i < accessMatrix.length ; i++)
{
chess[7][i].changeAccess(accessMatrix[7][i]);
}
}
public int getAccess()
{
return accessValue;
}
public int changeAccess(int newAccess)
{
int accessNew;
accessNew = newAccess;
return accessNew;
}
答案 0 :(得分:2)
在此代码中:
Board [] chessboard = new Board [8][8];
Board[8][8]
的类型为Board[][]
所以它应该用这种方式编写:
Board [][] chessboard = new Board [8][8];
(那么你必须在数组中创建每个Board()对象,我把它作为练习留给你)
在此代码中:
chessboard.fill();
您正在呼叫董事会的方法。您只能在Board对象上执行此操作,而不能在阵列上执行此操作。如果要在数组中的每个板对象上调用此方法,则必须执行以下操作:
for (int i = 0; i <8; i ++) {
for (int j = 0; j < 8; j ++){
chessboard[i][j].fill();
}
}
但我觉得还有更多,因为有一些混乱。我认为,棋盘是一块棋盘,而不是一块棋盘。您可能想要创建一个棋盘并填充一次。对?然后只需这样做:
Board chessboard = new Board();
chessboard.fill();