问题
my Task is to make an implementation of Conway's Game of Life. Therefor I need to create the class GameMap. In this class I will initialize an 2D Array. Therefor I use those two methods.
private static Cell[][] buildCellArray(int width, int height){
Cell[][] cellArray = new Cell[width][height];
int i;
int j;
for(i = 0; i < width; i++) {
for(j = 0; j < height; j++) {
cellArray[i][j] = new Cell();
}
}
return cellArray;
}
public GameMap(int sizeX, int sizeY) {
buildCellArray(sizeX, sizeY);
}
Now I want to access the cellArray to access a special Cell with the getCell(int posX, int posY) method. My question is how I can access the cellArray? I wanted to access it like this:
public Cell getCell(int posX, int posY){
return cellArray[posX][posY];
}
So that I get the Cell at a special position. I hope somebody can help me out.
So the complete code part is:
public class GameMap {
private static Cell[][] buildCellArray(int width, int height){
Cell[][] cellArray = new Cell[width][height];
int i;
int j;
for(i = 0; i < width; i++) {
for(j = 0; j < height; j++) {
cellArray[i][j] = new Cell();
}
}
return cellArray;
}
public GameMap(int sizeX, int sizeY) {
buildCellArray(sizeX, sizeY);
}
public Cell getCell(int posX, int posY){
return cellArray[posX][posY];
}
}
And the IDE says that cellArray in the method getCell is not a variable.
回答1:
The IDE says cellArray
cannot be resolve to a variable because it is local variable, to pass this problem just move Cell[][] cellArray = new Cell[width][height];
outside the buildCellArray()
.
public class GameMap {
Cell[][] cellArray;
private static Cell[][] buildCellArray(int width, int height){
int i;
int j;
for(i = 0; i < width; i++) {
for(j = 0; j < height; j++) {
cellArray[i][j] = new Cell();
}
}
return cellArray;
}
public GameMap(int sizeX, int sizeY) {
buildCellArray(sizeX, sizeY);
}
public Cell getCell(int posX, int posY){
return cellArray[posX][posY];
}
}
来源:https://stackoverflow.com/questions/63090328/how-can-i-access-the-cell-array-in-my-getcell-method-java