2016-02-19 72 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【尺寸】