簡體   English   中英

Java中的Null指針異常。 (數組中斷循環?)

[英]Null Pointer Exception in Java. (Broken for loop with array?)

因此,我已經閱讀了其他人的其他問題,但找不到適合我的解決方案。 我正在學習Java,因此決定制作一個基於控制台的簡單戰艦游戲,以測試一些基本的Java原理和實現。 就在程序的開始,我收到了NullPointerException錯誤。

這是我的代碼到錯誤點為止的樣子:

public class Battleship {

public static String[] xValues = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"};
public static String[] shipNames = {"patrol", "sub", "cruiser", "battle", "carrier"};
public static boolean isCollision = true;

//Create the Ship Array
public static Ship[] ships = new Ship[5];



public static void main(String[] args) {

    //Welcome the User
    System.out.println("Welcome to Battleship!\nLet's see how many tries it take to sink the ships!");

    //Now, let's make 5 kinds of ships: Patrol Boat, Submarine, Cruiser, Battleship, Carrier. Each has a different size.
    for (int i = 0; i < shipNames.length; i++){
        ships[i].setName(shipNames[i]);
    }

我唯一想到的可能是封裝問題,因為數組shipNames的靜態值不在main方法之外。 但是,將其放置在main方法中也不能解決該問題。 我以為垃圾回收可能是在main方法啟動時發生的,並且因為數組為空而破壞了數組,但是這也沒有用,因為調試器顯示shipNames.length = 5我感到困惑。 這里有什么想法嗎? 提前致謝。

您需要為陣列的每個插槽創建一個新的Ship對象。 請記住,對象的默認值為null

for (int i = 0; i < shipNames.length; i++){
        ships[i] = new Ship();
        ships[i].setName(shipNames[i]);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM