1

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?

2 Answers 2

4

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;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

How would you modify the values later after the array was initialized?
You can modify in the same way in constructor, initialiser block or after you have created the object
Check the update answer for different options to change values
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.