1

我不断收到此错误:

BattleshipCMDGame.GenerateShips(BattleshipCMDGame.java:33) 在 BattleshipCMDGame.main(BattleshipCMDGame.java:7) 的线程“主”java.lang.NullPointerException 中的异常

我要做的就是将我的方法中新创建的类类型数组返回到主方法中创建的空数组中。这是我的代码:

import java.util.*;

public class BattleshipCMDGame
{
public static void main(String[] args)
{
    Ship[] ship = GenerateShips(3);
    Scanner in = new Scanner(System.in);

    for (int i = 0; i < ship.length; i++)
    {
        System.out.println(ship[i].GetName() + " : Location - " + ship[i].GetLocation());
    }
}

public static Ship[] GenerateShips(int numShips)
{
    Ship[] ship = new Ship[numShips];
    Random rand = new Random();
    int randLoc;
    String prevRands = "";
    String randToString = "";

    for (int i = 0; i < ship.length; i++)
    {
        randLoc = 1 + rand.nextInt(7);
        randToString = Integer.toString(randLoc);

        for (int z = 0; z < ship.length; z++)
        {
            prevRands = "";

            if (ship[z].GetLocation() != 0)
            {
                prevRands += Integer.toString(ship[z].GetLocation());
            }
        }

        while (prevRands.contains(randToString))
        {
            randLoc = 1 + rand.nextInt(7);
            randToString = Integer.toString(randLoc);
        }

        ship[i] = new Ship("Ship no. " + (Integer.toString(i)), randLoc);
    }

    return ship;
}
}
4

3 回答 3

3
if (ship[z].GetLocation() != 0)

ship[z] 为空(null),这就是您收到错误的原因。您需要先填写您的阵列。

重要的是:ship array 存储引用而不是objects,所以这就是你需要先填充它的原因。所以

Ship[] ship = new Ship[10]

存储 10 个Ship引用(以null开头),即您需要自己分配的实际 Ship 对象。

于 2013-08-20T18:11:28.820 回答
3

您已在此行中创建了数组:

Ship[] ship = new Ship[numShips];

但是所有元素都是null,所以NullPointerException这一行的结果是:

if (ship[z].GetLocation() != 0)

您需要将Ship对象分配给数组中的位置,如下所示:

ship[z] = new Ship();
于 2013-08-20T18:11:34.797 回答
2

您应该初始化数组的每个元素:

ship[z] = new Ship();

顺便说一句,您应该使用以小写开头的方法名称,这是标准

于 2013-08-20T18:13:45.623 回答