【问题标题】:Can't initialize 2D array of objects in Java无法在 Java 中初始化二维对象数组
【发布时间】:2012-11-29 00:54:15
【问题描述】:

我正在尝试制作一个战舰游戏,为此我需要一个 2D 正方形数组,这是一个人可以选择的地方。然而,当我运行我的程序时,当我尝试调用 resetBoard() 函数时出现空指针异常。

战舰级:

public class Battleship
{
    private Square[][] squares;
    private boolean aircraftCarrierSunk;
    private boolean battleshipSunk;
    private boolean submarineSunk;
    private boolean patrolBoatSunk;
    private int boardSize;
    public int turns;

    public Battleship(int x)
    {
        squares = new Square[x][x];
//         for(int i = 0; i < boardSize; i++) //not sure if I need this
//         {
//             for(int j = 0; j < boardSize; j++)
//             {
//                 squares[i][j] = new Square();
//             }
//         }
        boardSize = x;
        aircraftCarrierSunk = false;
        battleshipSunk = false;
        submarineSunk = false;
        patrolBoatSunk = false;
    }

    public void resetBoard()
    {
        for(int i = 0; i < boardSize; i++)
        {
            for(int j = 0; j < boardSize; j++)
            {
                squares[i][j].setContents(0);
            }
        }
    }

司机:

public static void main (String [] args)
{
    Battleship game = new Battleship(5);        // play on a 5 by 5 board

    System.out.println("Battleship!");
    System.out.println("-----------\n");

    for (int gameNumber = 1; gameNumber <= 2; gameNumber++)
    {
        game.resetBoard();

【问题讨论】:

    标签: java arrays object


    【解决方案1】:

    知道了 - 取消注释 Battleship 中的行,然后将 boardSize = x; 移到 for 循环上方。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-22
      • 1970-01-01
      • 2017-07-23
      • 1970-01-01
      • 1970-01-01
      • 2013-12-15
      • 2013-11-21
      相关资源
      最近更新 更多