gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:15:50 24 4
gpt4 key购买 nike

我一直收到这个错误:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com