0

I am only beginning to learn Java and my first project is a simple version of a sea battle. Currently when compiling my project i get the following problem:

Exception in thread "main" java.lang.NullPointerException at SinkGame.PlaceDotComs(SinkGame.java:310) at SinkGame.<init>(SinkGame.java:19) at FirstVersion.main(FirstVersion.java:9)

Here are the relevant parts of the code: This is a part of SinkGame class

public class SinkGame 
{
   int gess_num;
   DotCom dotcoms[];
   Dot[] dots;
   boolean gameover;    

   public SinkGame()
   {
       gess_num = 0;
       gameover = false;
       dotcoms = new DotCom[3];
       dots = new Dot[49];

       PlaceDotComs (); //Problem is here
   }
...

PlaceDotComs method:

public void PlaceDotComs ()
{
    boolean dotcom_set = false;
    int dot_num = 0;

    //Sets all the board dots coordinates
    for (int i = 1; i < 8; i++)
    {
        for (int j = 1; j < 8; j++)
        {   
            dots[dot_num].SetRow(i); // Problem is here
            dots[dot_num].SetColumn(j);
            dot_num ++;
        }
    }
    //Sets dotcoms coordinates
    for (int i = 0; i < 3; i++)
    {
        dotcom_set = false;
        while (!dotcom_set)
        {
            dotcom_set = PlaceDotCom ((int)(Math.random()*GetActiveDotNumber()), i);
            if (dotcom_set)
                ExcludeFilledDots();
        }
    }
}

And my test class:

public class FirstVersion 
{
   public static void main (String[] args)
   {
       SinkGame new_game = new SinkGame(); //Problem here
       new_game.Game();
   } 
}

As far as i know Null pointer exception appears when an object has been declared but not created. But in this example i have created an object in constructor: dots = New Dot[49] before calling PlaceDotComs function. Could you please explain me what the problem is and how to solve it? Thank you very much!

  • 3
    `dots = new Dot[49];` creates an array that can hold `49` `Dot` references. It doesn't create **any** `Dot` references. So, `dots[dot_num].SetRow(i);` needs a `dots[dot_num] = new Dot();` before it. Also, please follow Java naming conventions. Lower case letters start method names. This looks *odd*. – Elliott Frisch Feb 28 '18 at 13:51
  • 1
    You have created an array, but you haven't initialized the single elements within the array. The array in your case contains only `null`s. That's why you get the exception. – dunni Feb 28 '18 at 13:51
  • 1
    You have created the array, but not filled it yet. Run a loop to create items in `dots`. – daniu Feb 28 '18 at 13:51
  • @ElliottFrisch, thank you very much for your reply. I have changed the code accordingly and now it works. – Nickolay R Feb 28 '18 at 13:58

0 Answers0