user289661
user289661

Reputation: 179

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

Please see image below:

enter image description here

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

Upvotes: 1

Views: 1078

Answers (2)

Sandesh Gupta
Sandesh Gupta

Reputation: 1195

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;
    }
}

Upvotes: 4

ashish gupta
ashish gupta

Reputation: 21

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.

Upvotes: 2

Related Questions