Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/384.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将返回值赋给新变量(Java)_Java - Fatal编程技术网

将返回值赋给新变量(Java)

将返回值赋给新变量(Java),java,Java,我已经有一段时间没有做过java编码了 我需要为需要自动化的业务(车间的一部分)构建一个应用程序,但这与我的问题无关 我被困在线路上:customerList.add(customer)//(WCIA类中addCustomer方法的一部分) 这也是我第一次被告知“将返回值赋给新变量”作为错误的一部分,所以我不太确定这意味着什么 代码:Main import java.util.ArrayList; public class WCIA { private final Arra

我已经有一段时间没有做过java编码了

我需要为需要自动化的业务(车间的一部分)构建一个应用程序,但这与我的问题无关

我被困在线路上:customerList.add(customer)//(WCIA类中addCustomer方法的一部分) 这也是我第一次被告知“将返回值赋给新变量”作为错误的一部分,所以我不太确定这意味着什么

代码:Main

    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<>();
}