在构造函数中初始化boolean [] [],然后在Java方法中将其返回

时间:2019-07-18 17:58:43

标签: java arrays constructor boolean

首先,对不起,如果我在此处格式化错误,因为这是我的第一篇文章。

我已经在线找到一个项目,并试图完成它。它正在尝试重新创建《人生游戏》。在一节中,它要求初始化变量'private boolean [] [] world'的实例,扩展构造函数以包括该变量,然后修改方法'boolean getCell(int i,int j)'以返回相应的在矩阵世界中的价值。

可以在这里找到整个项目:https://sites.google.com/site/dat170oop/lab2

我要指的是任务完成后的第1步。

到目前为止,我已经得到了NullPointerException,并且不确定从何处去。

到目前为止,我已经初始化了变量并扩展了构造函数。我还提供了只返回世界的getWorld方法。 修改getCell方法时,我遇到了一些问题。我首先尝试在该方法的参数中包含一个布尔b,但是觉得那不是前进的路。相反,我将变量i和j包含在世界的2D数组中,但这给了我NullPointerException。

    private int width, height, gen;
    private boolean[][] world; //my code

    public LifeModel (int w,int h, boolean[][] b) {
        width = w;
        height = h;
        world = b;  //my code
    }
//original code of project  for getCell method
    public boolean getCell(int i, int j) {      
        if (i==0 && j==0)
            System.out.println("LifeModel: Call to getCell(" + i + "," + j + ")");
         return(i+j) % 2 == 0;
//What I've done so far to change the method.
    public boolean getCell(int i, int j) {  

        world[2][4] = true;  //I think these should be somwhere in the main method instead
        world[4][4] = true;

        return world[i][j];
    }

我应该得到一个GameOfLife的模型,其中除了2之外的所有单元都死掉了,但是我却得到了NullPointerException。

对于任何关于我要去哪里的错误的解释或做什么的提示,我将不胜感激。

0 个答案:

没有答案