2012-03-21 56 views
0

我希望創建一個返回類型的數組的Java方法新手的java:ABCout,其中類ABCout被定義爲:在索引對象陣列

public class ABCout { 
    public int numOut; 
    public double[] myArray; 
} 

和Java方法是:

public ABCout[] GetABC(double myInput) throws Exception { 
    ABCout[] userABC = new ABCout[3]; 

    userABC[0].numOut = 10; 
    userABC[0].myArray = new double[1]; 
    userABC[0].myArray[0] = myInput; 
    /* here I only fill the 0'th element, but once working I will fill the others */ 

    return userABC; 
} 

但我得到的錯誤:java.lang.NullPointerException : null

任何人看到我做錯了什麼?

回答

4

您初始化了該數組,但未初始化其中的對象。你可能需要做的:

ABCout[] userABC = new ABCout[3]; 
for (int i = 0; i < userABC.length; ++i) { 
    userABC[i] = new ABCout(); 
} 

此外,您需要實例myArray

public class ABCout { 
    public int numOut; 
    public double[] myArray; 

    public ABCout() { 
     myArray = new double[10]; 
    } 
} 
+0

謝謝。我希望在類定義之外實例化,因爲長度將取決於myInput(在方法中接收:GetABC),儘管爲簡單起見未在上面以這種方式進行說明。 – ggkmath 2012-03-21 20:35:53

+0

這只是一個例子:) – MByD 2012-03-21 20:37:33

+0

很好,謝謝! – ggkmath 2012-03-21 20:49:45

0
//add this 
userABC[0] = new ABCount(); 

userABC[0].numOut = 10; 
    userABC[0].myArray = new double[1]; 
    userABC[0].myArray[0] = myInput; 

雖然你definetly需要做+你之前學習一些面向對象的編碼應閱讀一些基本的Java教程以及

2

您需要實例化您存儲在數組中的ABCout對象。

public ABCout[] GetABC(double myInput) throws Exception { 
    ABCout[] userABC = new ABCout[3]; 

    userABC[0] = new ABCout(); // instantiate 

    userABC[0].numOut = 10; 
    userABC[0].myArray = new double[1]; 
    userABC[0].myArray[0] = myInput; 
    /* here I only fill the 0'th element, but once working I will fill the others */ 

    return userABC; 
} 
2

您正在聲明一個ABCout數組,但您試圖在分配數組之前訪問該數組的第一個元素。

public ABCout[] GetABC(double myInput) throws Exception { 
    ABCout[] userABC = new ABCout[3]; 

    userABC[0] = new ABCout(); 
    userABC[0].numOut = 10; 
    userABC[0].myArray = new double[1]; 
    userABC[0].myArray[0] = myInput; 
    return userABC; 
} 
0

正如其他人所說,沒有第0個對象的實例化,因此您有運行時錯誤。你也可以這樣做:

public ABCout[] GetABC(double myInput) throws Exception { 
ABCout[] userABC = new ABCout[3]; 

ABCout current = new ABCout(); 
current.numOut = 10; 
current.myArray = new double[1]; 
current.myArray[0] = myInput; 

userABC[0] = current; 

return userABC; 
} 
相關問題