[英]How to solve returning an array into an empty array Java
我不斷收到此錯誤:
BattleshipCMDGame.GenerateShips(BattleshipCMDGame.java:33)的BattleshipCMDGame.main(BattleshipCMDGame.java:7)的線程“ main”中的java.lang.NullPointerException異常
我要做的就是將我方法中新創建的類類型數組返回到在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 = new Ship[10]
存儲10個Ship引用(以null開頭),這是您需要自己分配的實際Ship對象。
您已經在這一行中創建了數組:
Ship[] ship = new Ship[numShips];
但是所有元素都是null
,因此在此行上產生NullPointerException
:
if (ship[z].GetLocation() != 0)
您需要將Ship
對象分配給數組中的位置,如下所示:
ship[z] = new Ship();
您應該初始化數組的每個元素:
ship[z] = new Ship();
順便說一句,您應該使用以小寫字母開頭的方法名稱,這是標准的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.