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!