java - 用 1 行代码实例化和初始化对象数组

标签 java arrays

首先,如果标题有误导性,我深表歉意。我想用 Java 实现我自己的扫雷版本。当我创建一个对象数组并测试我的一个函数时,我得到了 NullPointerException。浏览 Stack Overflow 我设法解决了我的问题。然而事实证明,数组必须首先实例化,然后初始化。所以我要问的是:我可以实例化一个对象数组并同时初始化它吗?

MineSweeperMain.java

public class MineSweeperMain {
    public static void main(String[] args) {
        MineSweeper ms = new MineSweeper(9,9);
        int test;
        for (int i=0;i<9;i++)
            for (int j=0;j<9;j++)
            {
                ms.tile[i][j]=new Tile(); // can I initialize the array in the same line that I am instantiating it using the default constructor? 
            }
        test = ms.tile[0][0].getNeighbours();
        System.out.println("Test: " + test);
    }
}

瓷砖.java

public class Tile {
    int numNeighbours;
    boolean hasBomb;

    Tile() {
        numNeighbours = 0;
        hasBomb = false;
    }


    int getNeighbours() {
        return numNeighbours;
    }

    boolean hasBomb() {
        return hasBomb;
    }
}

扫雷.java

public class MineSweeper {
    Tile tile[][];

    MineSweeper(int x,int y) {
        tile = new Tile[x][y];
    }
}

谢谢。

编辑:使用tile[9][9]();也不起作用。

最佳答案

也许这就是你正在尝试做的......

 public static void main(String[] args) {
        MineSweeper ms = new MineSweeper(9,9);
        int test;
        // remove code here
        test = ms.tile[0][0].getNeighbours();
        System.out.println("Test: " + test);
    }

public class MineSweeper {
    Tile tile[][];

    MineSweeper(int x,int y) {
        tile = new Tile[x][y];
        // create Tiles here
        for (int i=0;i<x;i++)
            for (int j=0;j<y;j++)
                tile[i][j]=new Tile();
    }
}

关于java - 用 1 行代码实例化和初始化对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56064888/

相关文章:

java - SSLv2Hello - javax.net.ssl.SSLException : Received fatal alert: unexpected_message

c++ - 可调整大小的数组和摊销运行时

javascript - 使用 "if $(element).is(...)"检查数组元素

arrays - 如何将 Bluebird Promisification 与生成器 + 并行 Promise 结合使用

java - Sl4a运行Tasker任务并传递变量

PHP 键 => 值数组查找上一个和下一个条目

java - 列表的子类化如何工作?

java - Vertx EventBus 消费者中具有惰性集合的 JPA session

java - 如何压缩小字符串

Java正则表达式删除所有非字母数字字符,除了空格