CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Feb 2013
    Posts
    1

    Battleship program- need help

    First off, hello everyone.

    For a class project i must write a text based Battleship program. I am getting a NullPointerException in the following code and im not sure why exactly. I have 3
    classes: Game, SingleSpace, and Grid. The Grid object is a 2D array comprised of SingleSpace objects. And the Game is where my main function is.

    So heres a bit of the code. I am pretty new so it may be poorly coded.
    I originally had the array of type int but my professor wants us to have space objects so i figured that meant to have the array of type space.
    It worked when it was type int, but since i switched it to SingleSpace array, i am getting the error

    Name:  Space class.png
Views: 2084
Size:  19.7 KBName:  Grid class.png
Views: 2584
Size:  17.1 KBName:  Main.png
Views: 3000
Size:  22.1 KB


    Here is the error:
    Exception in thread "main" java.lang.NullPointerException
    at Grid.<init>(Grid.java:13)
    at Game.main(Game.java:12)

  2. #2
    Join Date
    May 2009
    Location
    Lincs, UK
    Posts
    298

    Re: Battleship program- need help

    In line 13 of the Grid class (where the exception is thrown) you are invoking the setValue method on an element of the playerBoard array, but the elements in this array are not initialised before this, so all the elements of the array are null (while you expect to have instances of SingleSpace). Before using any of these elements as SingleSpace objects you need to set them as instances of the SingleSpace class:
    Code:
    playerBoard[i][j] = new SingleSpace();
    And since in the constructor of SingleSpace you are initialising value to -1 you don't even need to invoke the setValue method.

    Also, why don't you use the ROWS and COLS constants in the for loops instead of 10?

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured