我不断收到此错误:
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;
}
}