将返回值赋给新变量(Java)
我已经有一段时间没有做过java编码了 我需要为需要自动化的业务(车间的一部分)构建一个应用程序,但这与我的问题无关 我被困在线路上:customerList.add(customer)//(WCIA类中addCustomer方法的一部分) 这也是我第一次被告知“将返回值赋给新变量”作为错误的一部分,所以我不太确定这意味着什么 代码:Main将返回值赋给新变量(Java),java,Java,我已经有一段时间没有做过java编码了 我需要为需要自动化的业务(车间的一部分)构建一个应用程序,但这与我的问题无关 我被困在线路上:customerList.add(customer)//(WCIA类中addCustomer方法的一部分) 这也是我第一次被告知“将返回值赋给新变量”作为错误的一部分,所以我不太确定这意味着什么 代码:Main import java.util.ArrayList; public class WCIA { private final Arra
import java.util.ArrayList;
public class WCIA {
private final ArrayList customerList = null;
public static void main(String[] args) {
short s =002;
Customer arno = new Customer();
arno.setName("Arno");
arno.setId(s);
arno.setEmail("arnomeye@gmail.com");
arno.setAddress("Somewhere");
arno.setPhoneNum("0727855201");
System.out.printf("%s",arno.getEmail());
WCIA wcia = new WCIA();
wcia.addCustomer(arno);
wcia.displayCustomers();
}
public void addCustomer (Customer customer)
{
customerList.add(customer); // <---Problem over here
}
public void displayCustomers()
{
for(int x=0;x<customerList.size();x++)
{
Customer cus = (Customer) customerList.get(x);
cus.DisplayCustomer();
}
}
}
您需要先实例化ArrayList,然后才能将元素分配给它。我猜,您可能会得到一个
NullPointerException
更改此行:
private final ArrayList customerList = null;
到
至少应该解决这个问题。我没有阅读您的其余代码,因此我不确定是否存在其他问题。
customerList
为null
,从未初始化。创建类型为ArrayList
的对象,并将其分配给该变量,然后再尝试添加到该变量。您应该声明列表及其元素类型的明确定义():
最后,作为良好实践,在构造函数中初始化它:
公共WCIA()
{
customerList=新的ArrayList();
}
你在哪里实例化了你的客户列表?谢谢你解决了所有问题,不过我觉得有点傻。
private final ArrayList customerList = null;
private final ArrayList customerList = new ArrayList();
private final List<Customer> customerList;
Customer cus = customerList.get(x);
public WCIA()
{
customerList = new ArrayList<>();
}