2016-02-19 73 views
0

我無法初始化一個對象數組。我不斷收到錯誤(NullPointerException),我嘗試了幾種不同的初始化方法。我相當新的Java(從C + +開始)。我在想也許我需要爲類Customer創建一個構造函數,但是當我嘗試它時,這不起作用。有任何想法嗎?提前致謝。 (這些只是我的代碼片段)空指針異常java數組初始化

更新:好吧,我更換了聲明,我仍然在幾行上得到nullpointerexception錯誤,這裏是更新後的代碼。我是否初始化客戶類的私有者是錯誤的? 再次感謝幫助人們,非常感謝。

更新2:所以經過一些修補之後,我創建了一個for循環,它分別初始化類對象數組的每個索引。謝謝一堆!

public static class ATM{ 
    private double funds = 100; 
    private int serial; 
    private String location = "UNKNOWN", bank_name; 
    private int succ_with = 0, fail_with =0; 
    private Customer[] customers = new Customer[10];///////updated here 
    public void custSet(String u, String b, int p, double bal, Customer[] customer, int index) 
    { 
     customer[index].user_name = u; 
     customer[index].bank_name = b;//second exception 
     customer[index].balance = bal; 
     customer[index].pin = p; 
    } 
    public void populateCust() 
    { 

     custSet("Alice","OtterUnion",1234,5000.0,customers,0);//3rd exception 
     custSet("Tom","OtterUnion",2000,200.0,customers,1); 
     custSet("Monica","OtterUnion",3000,50.0,customers,2); 
     custSet("Michael", "OtterUnion",7777,0.00,customers,3); 
     custSet("John","OtterUnion",8000,500.00,customers,4); 
     custSet("Jane","OtterUnion",2222,500.00,customers,5); 
     custSet("Robert","BOA",2323,200.00,customers,6); 
     custSet("Owen","BOA",4455,50.00,customers,7); 
     custSet("Chris","BOA",8787,10.00,customers,8); 
     custSet("Rebecca","BOA",8080,555.55, customers,9); 
    } 

    } 
public static class Customer{ 
    private String user_name, bank_name; 
    private int pin;//(first exception complaining about this, but when i 
    // change it to public the error goes away, so Ill just need to make a setter 
    private double balance; 
} 
+2

你從來沒有初始化的陣列,只宣佈它。 '私人客戶[]客戶=新客戶[10];' –

+0

好吧,我已經更新了我的帖子。我似乎仍然得到這個例外。我標記了編譯器抱怨它的地方。謝謝 –

回答

0

您使用前需要先來實例數組:客戶=新Cusomter【尺寸】