How can I access the Cell Array in my getCell method? (Java)

别说谁变了你拦得住时间么 提交于 2020-08-10 04:57:12

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!