问题
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