为什么不能为2D数组赋值? [英] Why can't I assign value to a 2D array?

查看:35
本文介绍了为什么不能为2D数组赋值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参见下图:

如何修改语法,以便能够为数组中的特定单元格分配特定值?

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

推荐答案

除非在初始化程序块或构造函数中编写值,否则不能在类主体中分配值.因此,如下所述在块中编写或在构造函数中分配.

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

这篇关于为什么不能为2D数组赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆