我不斷收到此錯誤:如何解決返回一個數組爲空數組的Java
Exception in thread "main" java.lang.NullPointerException at BattleshipCMDGame.GenerateShips(BattleshipCMDGame.java:33) at BattleshipCMDGame.main(BattleshipCMDGame.java:7)
所有我想要做的就是在我的方法新創建的類類型數組的形式返回到創建一個空數組主要方法。這裏是我的代碼:
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;
}
}
什麼是線33? –
正如遷移所指出的那樣,實施問題最好在SO而不是P.SE上處理。使用[null pattern](http://en.wikipedia.org/wiki/Null_Object_pattern)的問題,或傳遞null與空ArrayList的最佳選擇,或詢問[The Billion Dollar Mistake]中的點( http://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare)對P.SE更合適(雖然看起來,還有關於這個話題的其他問題)。 – 2013-08-20 18:13:41
順便說一句,特別是此代碼,請看[StringBuilder的](http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html),而不是做'prevRands + = Integer.toString(...);'你可能會創建並丟棄大量不必要的字符串。 – 2013-08-20 18:15:35