Why can't I assign value to a 2D array?

时光总嘲笑我的痴心妄想 提交于 2021-02-05 11:17:27

问题


Please see image below:

How can I modify the syntax so as to be able to assign specific values to specific cells in the array?


回答1:


You cannot assign values in the class body, unless you write it in initialiser block or constructor. So write in the block as mentioned below or assign in constructor.

public class Maze{

    private int maze[][] = new int[5][5];

    //Changing the value using initializer block
    {
        maze[1][1] = 1;
    }

    //Changing the value using constructor
    public Maze(){
        maze[1][1]=5;
    }

    public int[][] getMaze() {
        return maze;
    }

    public void setMaze(int[][] maze) {
        this.maze= maze;
    }

    public static void main(String args[]) {

        Maze maze = new Maze();
        int maze[][] = maze.getMaze();
        //Changing the value after creating object
        maze[1][2] = 5;
    }
}



回答2:


One simple way to assign values is by writing a custom method with Maze class and using it in your main method. For ex:

private void updateMaze(int val, int i, int j) {
   maze[i][j] = val;
}

Depending on the use case, different access modifier can be used.



来源:https://stackoverflow.com/questions/50166825/why-cant-i-assign-value-to-a-2d-array

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