java - 如何解决将数组返回到空数组Java

标签 java arrays reference

我一直收到这个错误:

Exception in thread "main" java.lang.NullPointerException at BattleshipCMDGame.GenerateShips(BattleshipCMDGame.java:33) at BattleshipCMDGame.main(BattleshipCMDGame.java:7)

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

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;
}
}

最佳答案

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

ship[z] 为空 (null),所以这就是您收到错误的原因。 您需要先填充您的 ship 数组。

重要的是:ship 数组存储引用 而不是对象,所以这就是为什么你需要先填充它。所以

Ship[] ship = new Ship[10]

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

关于java - 如何解决将数组返回到空数组Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18342085/

相关文章:

java - 为什么枚举在 java.utils 中被转换为 ArrayList 而不是 List?

java - 如何使用不同数量的命令行参数构建对象?

javascript - 当函数已有参数时如何获取调用者元素的引用

java - MySQL Java 存储过程给出错误 "Parameter index of 1 is out of range"

java - 使用 spring 加载应用程序上下文时出现异常

arrays - 在 MATLAB 中将混合数据元胞数组保存到 ascii 文件

c++ - 在不影响原始变量的情况下删除对变量的引用

java - 如何验证/强制类被垃圾收集

java - JPQL 元素集合 : getting all users which have at least one role of a list

python - 在 numpy 中使用多个排序键进行排序