我刚刚开始学习Java,我的第一个项目是海战的简单版本。目前在编译我的项目时遇到以下问题:
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)
以下是代码的相关部分: 这是SinkGame类的一部分
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方法:
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();
}
}
}
我的测试班:
public class FirstVersion
{
public static void main (String[] args)
{
SinkGame new_game = new SinkGame(); //Problem here
new_game.Game();
}
}
据我所知,当声明一个对象但未创建对象时,会出现Null指针异常。但是在这个例子中,我在构造函数中创建了一个对象:dots = New Dot [49],然后调用PlaceDotComs函数。 能否请您解释一下问题是什么以及如何解决? 非常感谢你!