我无法初始化对象数组。我一直收到错误(NullPointerException),我尝试了几种不同的初始化方法。我是java的新手(从c ++开始)。我想也许我需要为Customer类创建一个构造函数,但是当我尝试它时它不起作用。有任何想法吗?提前致谢。 (这些只是我代码的片段)
更新:好的,所以我替换了声明,我仍然在几行上得到nullpointerexception错误,这里是更新的代码。我初始化Customer类的私有错了吗? 再次感谢帮助人们,非常感谢。
更新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;
}
答案 0 :(得分:0)
您需要在使用之前实例化您的数组:customers = new Cusomter [size]