簡體   English   中英

數組初始化使空指針異常

[英]Array initialization gives null pointer exception

我最近在學習Java,並嘗試使用類。但是我無法初始化數組對象

 class Tablet
 {
    String S = null;
    void set(String a)
    {
        S = a;
    }
}

public class questions
{

public static void main(String args[])
{

    Tablet[] T = new Tablet[6];
    for(int i = 0;i<6;i++)
    {
        T[i].set("111"); // I get null pointer exception here
    }

    //solution(T,6);
} 
}

誰能告訴我我要去哪里錯了?

當你做

Tablet[] T = new Tablet[6];

您正在創建引用數組(即引用變量數組) ,這些引用數組未指向其他任何地方,即它們為null。您需要將對象分配給數組中上面創建的引用變量。

Tablet[] T = new Tablet[6];
    for(int i = 0;i<6;i++)
    {
        T[i]=new Tablet();
        T[i].set("111"); // No Null Pointer Exception Now
    }

您需要初始化數組的索引

class Tablet {

    String S = null;

    void set(String a) {
        S = a;
    }
}

class questions {

    public static void main(String args[]) {

        Tablet[] T = new Tablet[6];
        for (int i = 0; i < 6; i++) {
            T[i] = new Tablet();
            T[i].set("111"); // I get null pointer exception here
        }

        //solution(T,6);
    }
}

您創建了一個數組(一個用於幾個Tablet對象的支架),但實際上並沒有創建任何Tablet放入其中。 現在, T (實際上應該是小寫的; T看起來像一個常量和一個類型參數)具有以下內容:

T: {null, null, null, null, null, null}

您需要創建new Tablet ,並將它們放入數組中,也許像這樣:

for(int i = 0; i < array.length /* don't hardcode the size twice */; i++) {
    array[i] = new Tablet();
    array[i].set("111");
}

您已經初始化了數組。 但是,數組中的元素指向null。 所以很明顯,如果您嘗試在空指針上調用方法,則會得到一個空指針異常。 您必須使用new關鍵字初始化數組中的每個對象。

您必須添加一個T [i] = new Tablet(); 在對其執行任何功能之前初始化變量。

T[i]=new Tablet();
T[i].set("111");

在for循環中執行此操作

暫無
暫無

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

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